Swift function (method)

Time:2022-5-26

1、 Definition of function

be careful ⚠️: By default, the function parameter is let, and the value of the parameter cannot be changed
Form of function

Function parameter name (func) - > (return value){
   Return return value
}

Function parameters are optional, and the number of parameters can be one or more
The return value of the function is optional, as shown in the following example

1. No parameter, no return value

//Mark: -- function without return parameter
func sayHello(){
    print("Hellow")
}

2. There are parameters and no return value

func sayHelloToSomeone(_ name:String){
    print("Hellow \(name)")
}

3. No parameter has return value

func p() -> CGFloat{
    return 3.14
}

4. There are parameters and return values

func sum(_ v1:Int,_ v2:Int) -> Int{
    return  v1 + v2
}

2、 Implicit return

If the whole function body is a single expression, the function will implicitly return this expression (that is, the keyword return can be omitted)
for example

func sum(_ v1:Int,_ v2:Int) -> Int{
     v1 + v2
}

3、 Return tuple: realize multiple return values

example

func calculate(v1: Int, v2: Int) -> (sum: Int, difference: Int, average: Int) {
    let sum = v1 + v2
    return (sum, v1 - v2, sum >> 1)
}

4、 Parameter labels in functions

The parameters in the function can be labeled
for example

func sum(unmber1 v1:Int,unmber1 v2:Int) -> Int{
    return  v1 + v2
}

Call mode
sum(unmber1: 10, unmber1: 20)

Unmber1 and unmber1 here are the labels of parameters

Another example

func goToWork(at time: String) {
    print("this time is \(time)")
}

Call mode
goToWork(at: "08:00")

At here is the label of the parameter

The function of the tag is to prompt that the tag can be used_ To replace
as

func sum(_ v1:Int,_ v2:Int) -> Int{
    return  v1 + v2
}

5、 Default arguments in functions

The default parameter in the function refers to the parameter assigned with the initial value. When calling the function, the default parameter can be passed or not

func check(name: String = "nobody", age: Int, job: String = "none") {

    print("name=\(name), age=\(age), job=\(job)")
}

check(name: "Jack", age: 20, job: "Doctor") // name=Jack, age=20, job=Doctor
check(name: "Rose", age: 18) // name=Rose, age=18, job=none
check(age: 10, job: "Batman") // name=nobody, age=10, job=Batman
check(age: 15) // name=nobody, age=15, job=none

For example, in the above functions, both name and job have default values, and age has no default value. Therefore, when calling the function, except for age, it can not be empty

be careful ⚠️: When there are default parameters in the function, you must pay attention to the required parameters. Sometimes the label cannot be omitted
such as

func test(_ first: Int = 10, middle: Int, _ last: Int = 30) { }
test(middle: 20)

If the label of the middle parameter of the above function is omitted, you will not know which parameter you passed when calling the test function, so an error will be reported
As shown below

Swift function (method)

Screenshot 2021-12-15 2.50.10 PM png

6、 Variable arguments in functions

In other words, the parameters of the function are not fixed, and can be one or more
for example

func sum(_ numbers: Int...) -> Int {
    var total = 0
    for number in numbers {
        total += number
    }
    return total
}

sum(10, 20, 30, 40)

be careful ⚠️:
1. A function can have at most one variable parameter
2. A parameter immediately following a variable parameter cannot omit a label
as

func test(_ numbers: Int..., string: String, _ other: String) { }
test(10, 20, 30, string: "Jack", "Rose")

The string parameter of the test function cannot omit the label

If omitted, an error will be reported, as shown in the figure below

Swift function (method)

Screenshot 2021-12-15 2.58.53 PM png

The reason is: if the label of the parameter immediately following the variable parameter is omitted, the variable parameter does not know where to end, and then the latter parameter is regarded as a variable parameter, all will report an error

7、 Input output function (inout) in function

You can define an input / output parameter with inout:
Function: external arguments can be modified inside the function

for example

func swapValues(_ v1: inout Int, _ v2: inout Int) {
    let tmp = v1
    v1 = v2
    v2 = tmp
}
var num1 = 10
var num2 = 20
swapValues(&num1, &num2)

Variable parameters cannot be marked as inout
The inout parameter cannot have a default value
The inout parameter can only be passed in values that can be assigned multiple times
The essence of inout parameter is address passing (reference passing is to pass the address of the parameter and then modify the value stored in the address according to the address)

8、 Function overloading

rule
1. Same function name
2. Different number of parameters 𞓜 different parameter types | different parameter labels

func sum(v1: Int, v2: Int) -> Int {
    v1 + v2
}

//Different number of parameters

func sum(v1: Int, v2: Int, v3: Int) -> Int {
    v1 + v2 + v3
}

//Different parameter types

func sum(v1: Int, v2: Double) -> Double {
    Double(v1) + v2
}

//Different parameter types

func sum(v1: Double, v2: Int) -> Double {
    v1 + Double(v2)
}

//Different parameter labels

func sum(_ v1: Int, _ v2: Int) -> Int {
    v1 + v2
}

//Different parameter labels

func sum(a: Int, b: Int) -> Int {
    a + b
}

be careful ⚠️:
The return value type is independent of function overloading
When the default parameter value is used with function overloading to generate ambiguity, the compiler will not report an error (in C + +)
When variable parameters, omitted parameter labels and function overloading are used together to produce ambiguity, the compiler may report an error

9、 Inline function

Use @ inline (never) to decorate the function, which will never be inlined (even if compiler optimization is turned on)

@inline(never) func test() {
  print("test") 
}

After using the @ inline (_always) modifier function to enable compiler optimization, even if the code is very long, it will be inlined (except recursive calling functions and dynamically distributed functions)

@inline(__always) func test() {
 print("test")
 }

In release mode, the compiler has started optimization and will automatically determine which functions need to be inlined, so @ inline is not necessary