Swift function
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:
Function definition
Swift defines functions using keywords func
.
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 ->
the return value type of the function is defined after.
Grammar
func funcname(formal parameter) -> returntype
{
Statement1
Statement2
……
Statement N
return parameters
}
Example
Below we define a function named 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"))
The output of the above program execution is as follows:
www.runoob.com
Function call
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 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"))
The output of the above program execution is as follows:
www.runoob.com
Function parameter
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 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"))
The output of the above program execution is as follows:
Rookie Tutorial:www.runoob.com
Google:www.google.com
Function without parameter
We can create functions without arguments.
Syntax:
func funcname() -> datatype {
return datatype
}
Example
import Cocoa
func sitename() -> String {
return "Rookie Tutorial"
}
print(sitename())
The output of the above program execution is as follows:
Rookie Tutorial
The tuple returns a value as a function
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 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 name
The output of the above program execution is as follows:
The minimum value is -6, the maximum value is 109
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 (Int, Int)?
or (String, Int, Bool)?
Note that optional tuple types such as (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.
Front 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.
To safely handle this “empty array” problem, set 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 output of the above program execution is as follows:
The minimum value is -6,the maximum value is 109
No return value function
The following is 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")
The output of the above program execution is as follows:
Rookie Tutorial official website:http://www.runoob.com
Function parameter name
Function parameters have an external parameter name and a local parameter name.
Local parameter name
The local parameter name is used 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 in the function body.
import Cocoa
func sample(number: Int) {
print(number)
}
sample(number: 1)
sample(number: 2)
sample(number: 3)
The output of the above program execution is as follows:
1
2
3
External parameter name
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:
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 output of the above program execution is as follows:
125
Note that if you provide an external parameter name, the function must use the external parameter name when it is called.
Variable parameter
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.
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")
The output of the above program execution is as follows:
4
3
5
4.5
3.1
5.6
Google
Baidu
Runoob
Constants, variables, and Istroke O parameters
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 inout
keyword, so that you can change the value of this parameter.
For example:
func getName(_ name: inout String).........
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.
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.
It is important to note that someInt
and anotherInt
in the incoming swapTwoInts(_:_:)
the prefix of & is added before the function.
The output of the above program execution is as follows:
The current value of x is 5, the current value of y is 1
Function types and their use
Each function has a specific function type, which consists of the parameter type and return type of the function.
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.
Examples are as follows:
import Cocoa
func inputs(no1: Int, no2: Int) -> Int {
return no1/no2
}
print(inputs(no1: 20, no2: 10))
print(inputs(no1: 36, no2: 6))
The output of the above program execution is as follows:
2
6
The above functions define two Int
parameter type, and the return valueis also Int
type.
Next, let’s take a look at the following function, which defines the parameter as String
type, the return value is String
type.
func inputstr(name: String) -> String {
return name
}
A function can also define a function that has no parameters and no return value, as shown below:
import Cocoa
func inputstr() {
print("Rookie Tutorial")
print("www.runoob.com")
}
inputstr()
The output of the above program execution is as follows:
Rookie Tutorial
www.runoob.com
Use function types
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:
var addition: (Int, Int) -> Int = sum
Parsing:
“define a variable called addition, with both the parameter and the return value type being Int
and let the new variable point to sum
function “.
sum
and addition
are the same type, so the above operation is legal.
Now, you can use 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))")
The output of the above program execution is as follows:
Output: 129