A separate block of code that the Swift function uses to accomplish a specific task.
Swift uses a unified syntax to represent simple C-style functions to complexobjective-C-style methods.
Function declaration: tells the compiler the name of the function, the return type and parameters.
Function definition: provides the entity of the function.
The Swift function contains the parameter type and the return value type: Swift defines functions using keywords When defining a function, you can specify one or more input parameters and areturn value type. Each function has a function name to describe its function. This function iscalled by the function name and the parameter values of the corresponding type. The parameters of the function must be passed in the same order as theparameter list. The argument of the function must be passed in the same order as the formal parameter list Below we define a function named The output of the above program execution is as follows: We can call the function by the function name and the parameter values of the corresponding type, and the parameters of the function must be passed inthe same order as the parameter list. Below we define a function named The output of the above program execution is as follows: A function can accept one or more parameters, which are contained in parentheses of the function, separated by commas. The following example is directed to the function The output of the above program execution is as follows: We can create functions without arguments. The output of the above program execution is as follows: The function return value type can be string, integer, floating point, and so on. Tuples are similar to arrays, except that elements in tuples can be of any type, using parentheses. You can use the tuple type to return multiple values from the function as a compound value. In the following example, a file named The output of the above program execution is as follows: If you are not sure that the returned tuple is not nil, then you can return an optional tuple type. You can define an optional tuple by placing a question mark after the closing parenthesis of the tuple type, such as Note that optional tuple types such as Front To safely handle this “empty array” problem, set the The output of the above program execution is as follows: The following is The output of the above program execution is as follows: Function parameters have an external parameter name and a local parameter name. The local parameter name is used within the implementation of the function. In the above example, number is a local parameter name and can only be used in the function body. The output of the above program execution is as follows: You can specify the external parameter name before the local parameter name,separated by a space, and the external parameter name is used for the parameters passed to the function when the function is called. You can define the following two function parameter names and call them as follows: The output of the above program execution is as follows: Note that if you provide an external parameter name, the function must use the external parameter name when it is called. Variable parameters can accept zero or more values. When a function is called, you can specify the function parameters with variable parameters, the number of which is uncertain. Variable parameters are defined by adding (…) after the variable type name. The output of the above program execution is as follows: Generally speaking, the parameters defined in the function are constant parameters by default, that is, you can only query and use this parameter, and you cannot change its value. If you want to declare a variable parameter, you can add the For example: At this point, the name value can be changed in the function. Generally speaking, the default parameter passing is called by passing a value instead of passing a reference. So the parameter passed in changes within the function and does not affect the original parameter. All that is passed in is a copy of this parameter. When the passed parameter is used as the input and output parameter, the & character needs to be added to the parameter name to indicate that the valuecan be modified by the function. It is important to note that The output of the above program execution is as follows: Each function has a specific function type, which consists of the parameter type and return type of the function. Examples are as follows: The output of the above program execution is as follows: The above functions define two Next, let’s take a look at the following function, which defines the parameter as A function can also define a function that has no parameters and no return value, as shown below: The output of the above program execution is as follows: In Swift, using function types is like using other types. For example, you can define a constant or variable of type function and assign the appropriate function to it: Parsing: “define a variable called addition, with both the parameter and the return value type being Now, you can use The output of the above program execution is as follows: Output: 129 9.28.1. Function definition #
func
.
->
the return value type of the function is defined after. 9.28.2. Grammar #
func funcname(formal parameter) -> returntype
{
Statement1
Statement2
……
Statement N
return parameters
}
9.28.3. Example #
runoob
the data type of the formal parameter is
String
the return value is also
String
:import Cocoa
func runoob(site: String) -> String {
return (site)
}
print(runoob(site: "www.runoob.com"))
www.runoob.com
9.28.4. Function call #
runoob
formal parameter
site
The data type of
String
and then the arguments we pass by calling the function must also
String
type, after the argument is passed into the function body, it will be returned directly, and the returned data type is
String
.import Cocoa
func runoob(site: String) -> String {
return (site)
}
print(runoob(site: "www.runoob.com"))
www.runoob.com
9.28.5. Function parameter #
runoob
transfer station roll call
name
and site address
site
:import Cocoa
func runoob(name: String, site: String) -> String {
return name + site
}
print(runoob(name: "Rookie Tutorial:", site: "www.runoob.com"))
print(runoob(name: "Google:", site: "www.google.com"))
Rookie Tutorial:www.runoob.com
Google:www.google.com
9.28.6. Function without parameter #
9.28.7. Syntax: #
func funcname() -> datatype {
return datatype
}
9.28.8. Example #
import Cocoa
func sitename() -> String {
return "Rookie Tutorial"
}
print(sitename())
Rookie Tutorial
9.28.9. The tuple returns a value as a function #
minMax(_:)
the function is used in a
Int
find the minimum and maximum values in the array.import Cocoa
func minMax(array: [Int]) -> (min: Int, max: Int) {
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count] {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
let bounds = minMax(array: [8, -6, 2, 109, 3, 71])
print("The minimum value is \(bounds.min) ,The maximum value is \(bounds.max)")
minMax(_:)
the function returns one that contains two
Int
values that are marked as
min
and
max
, so that when querying the return values of functions, they can be accessed by nameThe minimum value is -6, the maximum value is 109
(Int,
Int)?
or
(String,
Int,
Bool)?
(Int,
Int)?
and tuples contain optional types such as
(Int?,
Int?)
is different. Optional tuple type, the entire tuple is optional, not just the value of each element in the tuple.
minMax(_:)
function returns a function that contains two
Int
the tuple of the value. However, the function does not perform any security checks on the incoming array, if
array
parameter is an empty array, asdefined above
minMax(_:)
trying to access
array[0]
a runtime error is triggered when the.
minMax(_:)
Function is rewritten to use an optional tuple to return the type, and when the array is empty
nil
:import Cocoa
func minMax(array: [Int]) -> (min: Int, max: Int)? {
if array.isEmpty { return nil }
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count] {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) {
print("The minimum value is \(bounds.min),the maximum value is \(bounds.max)")
}
The minimum value is -6,the maximum value is 109
9.28.10. No return value function #
runoob(_:)
function, which takes the parameters of thewebsite of the rookie tutorial, does not specify the return type, and outputs directly
String
value instead of returning it:import Cocoa
func runoob(site: String) {
print("Rookie Tutorial official website:\(site)")
}
runoob(site: "http://www.runoob.com")
Rookie Tutorial official website:http://www.runoob.com
9.28.11. Function parameter name #
9.28.12. Local parameter name #
func sample(number: Int) {
println(number)
}
import Cocoa
func sample(number: Int) {
print(number)
}
sample(number: 1)
sample(number: 2)
sample(number: 3)
1
2
3
9.28.13. External parameter name #
import Cocoa
func pow(firstArg a: Int, secondArg b: Int) -> Int {
var res = a
for _ in 1..<b {
res = res * a
}
print(res)
return res
}
pow(firstArg:5, secondArg:3)
125
9.28.14. Variable parameter #
import Cocoa
func vari<N>(members: N...){
for i in members {
print(i)
}
}
vari(members: 4,3,5)
vari(members: 4.5, 3.1, 5.6)
vari(members: "Google", "Baidu", "Runoob")
4
3
5
4.5
3.1
5.6
Google
Baidu
Runoob
9.28.15. Constants, variables, and Istroke O parameters #
inout
keyword, so that you can change the value of this parameter.func getName(_ name: inout String).........
9.28.16. Example #
import Cocoa
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
var x = 1
var y = 5
swapTwoInts(&x, &y)
print("The current value of x \(x), the current value of y \(y)")
swapTwoInts(_:_:)
function simply exchanges the values of an and b. Thisfunction first saves the value of a to a temporary constant
temporaryA
,then assign the value of b to a, and finally set the
temporaryA
assign a value to b.
someInt
and
anotherInt
in the incoming
swapTwoInts(_:_:)
the prefix of & is added before the function.The current value of x is 5, the current value of y is 1
9.28.17. Function types and their use #
func inputs(no1: Int, no2: Int) -> Int {
return no1/no2
}
inputs
there are two function types
Int
type parameters (no1, no2) and return a
Int
the value of type.import Cocoa
func inputs(no1: Int, no2: Int) -> Int {
return no1/no2
}
print(inputs(no1: 20, no2: 10))
print(inputs(no1: 36, no2: 6))
2
6
Int
parameter type, and the return valueis also
Int
type.
String
type, the return value is
String
type.func inputstr(name: String) -> String {
return name
}
import Cocoa
func inputstr() {
print("Rookie Tutorial")
print("www.runoob.com")
}
inputstr()
Rookie Tutorial
www.runoob.com
9.28.18. Use function types #
var addition: (Int, Int) -> Int = sum
Int
and let the new variable point to
sum
function “.
sum
and
addition
are the same type, so the above operation is legal.
addition
to call the assigned function:import Cocoa
func sum(a: Int, b: Int) -> Int {
return a + b
}
var addition: (Int, Int) -> Int = sum
print("Output results: \(addition(40, 89))")