Swift functions
Swift functions are independent blocks of code used to accomplish specific tasks.
Swift uses a unified syntax to represent simple C-style functions to complex Objective-C style methods.
Function declaration: Tell the compiler the name, return type and parameters of the function.
Function definition: Provides the entity of the function.
Swift functions include parameter types and return value types:
Function definition
Swift defines functions using the keyword func .
When defining a function, you can specify one or more input parameters and a return value type.
Each function has a function name to describe its function. This function is called through the function name and parameter values of the corresponding types. The parameters of the function must be passed in the same order as the parameter list.
The actual parameters of the function must be passed in the same order as the formal parameter list, -> and then define the return value type of the function.
Grammar
func funcname(形参) -> returntype { Statement1 Statement2 …… Statement N return parameters }
Example
Below we define a function named php, the data type of the formal parameter is String, and the return value is also String:
import Cocoa func php(site: String) -> String { return site } print(php("www.php.cn"))
The execution output of the above program is:
www.php.cn
Function call
We can call the function through the function name and the parameter value of the corresponding type, and the order in which the parameters of the function are passed Must be the same as parameter list.
Below we define a function named php. The data type of the formal parameter site is String. Then the actual parameters we pass when calling the function must also be of String type. After the actual parameters are passed into the function body, they will be directly Return, the returned data type is String.
import Cocoa func php(site: String) -> String { return site } print(php("www.php.cn"))
The execution output of the above program is:
www.php.cn
Function parameters
The function can accept one or more parameters, and we can also use tuples. Pass one or more parameters to the function:
import Cocoa func mult(no1: Int, no2: Int) -> Int { return no1*no2 } print(mult(2, no2:20)) print(mult(3, no2:15)) print(mult(4, no2:30))
The execution output of the above program is:
40 45 120
Function without parameters
We can create a function without parameters function.
Grammar:
func funcname() -> datatype { return datatype }
Example
import Cocoa func sitename() -> String { return "php中文网" } print(sitename())
The above program execution output result is:
php中文网
Tuple as function return value
The function return value type can be string, integer, floating point, etc.
Tuples are similar to arrays. The difference is that the elements in the tuple can be of any type and use parentheses.
You can use the tuple type to return multiple values as a composite value from a function.
In the following example, a function named minMax(_:) is defined, which is used to find the minimum and maximum values in an Int 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([8, -6, 2, 109, 3, 71]) print("最小值为 \(bounds.min) ,最大值为 \(bounds.max)")
The minMax(_:) function returns a tuple containing two Int values, which are labeled min and max so that they can be accessed by name when querying the return value of the function.
The execution output of the above program is:
最小值为 -6 ,最大值为 109
If you are not sure that the returned tuple must not be nil, then you can return an optional tuple type.
You can define an optional tuple by placing a question mark after the closing bracket of the tuple type, such as (Int, Int)? or (String, Int, Bool)?
Note
Optional tuple types such as(Int, Int)?
are the same as tuples containing optional types such as(Int?, Int?)
Yes Unlike the .optional tuple type, the entire tuple is optional, not just each element value in the tuple.
The previous minMax(_:)
function returns a tuple containing two Int
values. However, the function will not perform any security checks on the incoming array. If the array
parameter is an empty array, minMax(_:)
as defined above will fail when trying to access the array[ 0]
will trigger a runtime error.
To handle this "empty array" problem safely, the minMax(_:)
function is rewritten to use an optional tuple return type and return 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([8, -6, 2, 109, 3, 71]) { print("最小值为 \(bounds.min),组大值为 \(bounds.max)") }
The execution output of the above program is:
最小值为 -6,组大值为 109
No return value function
The following is another php(_:) function version, this function receives the php Chinese website official website parameter, does not specify the return value type, and directly outputs the String value instead of returning it:
import Cocoa func php(site: String) { print("php中文网官网:\(site)") } php("http://www.php.cn")
The output result of the above program execution is:
php中文网官网:http://www.php.cn
Function parameter name
Function parameters have an external parameter name and a local parameter name.
Local parameter names
Local parameter names are used internally within the implementation of the function.
func sample(number: Int) { println(number) }
In the above example, number is a local parameter name and can only be used within the function body.
import Cocoa func sample(number: Int) { print(number) } sample(1) sample(2) sample(3)
The above program execution output result is:
1 2 3
External parameter name
You can specify the external parameter name before the local parameter name, separated by spaces in the middle, the external parameter name is For the parameters passed to the function when the function is called.
As follows you can define the following two function parameter names and call it:
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)
The execution output of the above program is:
125
Note
If you If an external parameter name is provided, the external parameter name must be used when the function is called.
Variable parameters
Variable parameters can accept zero or more values. When calling a function, you can use variable parameters to specify function parameters, and the number is undetermined.
Variable parameters are defined by adding (...) after the variable type name.
import Cocoa func vari<N>(members: N...){ for i in members { print(i) } } vari(4,3,5) vari(4.5, 3.1, 5.6) vari("Google", "Baidu", "php")
The execution output result of the above program is:
4 3 5 4.5 3.1 5.6 Google Baidu php
Constant, variable and I/O parameters
Generally, 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 var in front, so that the value of the parameter can be changed.
For example:
func getName(var id:String).........
At this time, the id value can be changed in the function.
Generally, the default parameter passing is called by value, not by reference. Therefore, the parameter passed in is changed within the function, and it does not affect the original parameter. What is passed in is just a copy of this parameter.
Variable parameters, as mentioned above, can only be changed within the function body. If you want a function to modify the value of a parameter, and you want these modifications to persist after the function is called, then you should define the parameter as an In-Out Parameters.
When defining an input and output parameter, add the inout keyword before the parameter definition. An input and output parameter has the value passed into the function, this value is modified by the function, and then passed out of the function, replacing the original value.
Example
import Cocoa func swapTwoInts(var a:Int,var b:Int){ let t = a a = b b = t } var x = 0,y = 100 print("x = \(x) ;y = \(y)") swapTwoInts(x, b:y) print("x = \(x) ;y = \(y)")
The execution output of the above program is:
x = 0 ;y = 100 x = 0 ;y = 100<pThe parameter passed in at this time is a copy of the original value, so this function will not exchange the two values. < p="">
The modification method is to use the inout keyword:
import Cocoa func swapTwoInts(inout a:Int,inout b:Int){ let t = a a = b b = t } var x = 0,y = 100 print("x = \(x) ;y = \(y)") swapTwoInts(&x, b:&y) print("x = \(x) ;y = \(y)")
The output result of the above program execution is:
x = 0 ;y = 100 x = 100 ;y = 0
Function type and usage
Each function has a specific function type, which consists of the function's parameter type and return type.
func inputs(no1: Int, no2: Int) -> Int { return no1/no2 }
The example is as follows:
import Cocoa func inputs(no1: Int, no2: Int) -> Int { return no1/no2 } print(inputs(20,no2:10)) print(inputs(36,no2:6))
The above program execution output result is:
2 6
The above function defines two Int parameter types, and the return value is also of Int type.
Next let’s take a look at the following function. The function defines parameters as String type and return value as String type.
Func inputstr(name: String) -> String { return name }
The function can also define any parameters and types, as shown below:
import Cocoa func inputstr() { print("php中文网") print("www.php.cn") } inputstr()
The above program execution output result is:
php中文网 www.php.cn
Use function type
In Swift, you work with function types just like any other type. For example, you can define a constant or variable of type function and assign the appropriate function to it: The variable, parameter and return value types are all
Int, and let this new variable point to the
sum function". sum
and addition
have the same type, so the above operation is legal.
Now, you can use addition to call the assigned function:
The execution output of the above program is: var addition: (Int, Int) -> Int = sum
import Cocoa
func sum(a: Int, b: Int) -> Int {
return a + b
}
var addition: (Int, Int) -> Int = sum
print("输出结果: \(addition(40, 89))")
输出结果: 129The output result of the above program execution is:
import Cocoa func sum(a: Int, b: Int) -> Int { return a + b } var addition: (Int, Int) -> Int = sum print("输出结果: \(addition(40, 89))") func another(addition: (Int, Int) -> Int, a: Int, b: Int) { print("输出结果: \(addition(a, b))") } another(sum, a: 10, b: 20)Function nesting Function nesting refers to defining a new function within a function, and external functions can call functions defined within the function. The example is as follows:
输出结果: 129 输出结果: 30
The execution output of the above program is:
import Cocoa func calcDecrement(forDecrement total: Int) -> () -> Int { var overallDecrement = 0 func decrementer() -> Int { overallDecrement -= total return overallDecrement } return decrementer } let decrem = calcDecrement(forDecrement: 30) print(decrem())