This post first appeared on my personal blog

The function definitions

  • The parameter defaults to let and can only be let
  1. No parameter no return value

You can omit Void or not, all three of the following

func sayHello() {print("hello")
}

func sayHello() -> (){
    print("hello")
}

func sayHello() -> (Void){
    print("hello")}Copy the code
  1. No parameter has a return value
	 func pi() -> Double {
        return3.1415}Copy the code
  1. There are parameters and return values
    
    func sum(a: Int, b: Int) -> Int {
        return a + b
    }
Copy the code

Implicit return

  • If the body of a function is a single expression, then the function returns that expression. For example, the above code can be written without return
    func sum(a: Int, b: Int) -> Int {
        a + b
    }
Copy the code

Return tuples: Multiple return values can be implemented

For example,

  func calculate(a: Int, b: Int) -> (sum: Int, average: Int) {
        let sum = a + b
        returnCalculate (a: 2, b: 8) return (sum: 10, average: 5)Copy the code

Documentation comments

  • Position the cursor on the start line of the object to which you want to add the comment document, or on the blank line above it. Press Command + Option + / to ⌘ + ⌥ + /. (For Windows keyboard, Win + ALT + /)

For example, add comments to the code above

/// /// -parameters: /// -a: the first parameter /// -b: the second parameter /// - Returns: the sum of the two Parameters func sum(a: Int, b: Int) -> Int {return a + b
    }
Copy the code

Parameters of the label

  • You can modify the parameter label
 func goToWork(at time: String) -> () {
        print("this time is \(time)")}Copy the code
  • You can omit parameter labels by using underscore _
 func sum2(_ a: Int, _ b: Int) -> Int {
        return a + b
    }
Copy the code

Default Parameter Value

  • Arguments can have default values as in C++
  • But there is a limitation to default parameters in C++ : they must be set from right to left. Swift has parameter tags, so there is no such limitation
Definition: func check(name: String ="jack", age: Int, job: String = "teacher") {
        print("name = \(name), age = \(age), job = \(job)"Name = jack, age = 22, job = teacherCopy the code

Variable parameter

Such as:

 func sum(_ numbers: Int...) -> Int{
        var total = 0
        for num in numbers {
            total += num
        }
        returnTotal} : sum(1,2,3)Copy the code
  • A function can have at most one variable argument
  • Parameters immediately following a variable parameter cannot omit the parameter label (otherwise it will compile ambiguously)

For example,

// The string argument cannot omit the label functest(_ numers: Int... , string: String) -> Void { }Copy the code

Input/output parameter

  • We said that the parameter can only be let, but if we want to internally modify the value of the external argument, we can use inpot to define the input and output parameters

For example,

   func swapValues(_ v1: inout Int, _ v2: inout Int) {
        letVar num1 = 10 var num2 = 20 swapValues(&num1, &num2)print("num1 = \(num1), num2 = \(num2)"Num1 = 20, num2 = 10Copy the code

Note:

  • A variable parameter cannot be marked as input
  • The input parameter cannot have a default value
  • The input argument is essentially address passing (reference passing)
  • The input argument can only be passed in values that can be assigned more than once

Function overloading

The rules

  • Same function name
  • The number of parameters is different or the parameter type is different or the parameter label is different

Points to note are:

  • The return value type is independent of function overloading
  • The compiler does not report ambiguities when using default parameter values with function overloads (c++ does).

For example,

func sum(v1: Int, v2: Int) -> Int { v1 + v2 } func sum(v1: Int, v2: Int, v3: Sum (v1: Int, v2: Int) sum(v1: Int, v2: Int) sum(v1: 10, v2: 20)Copy the code
  • When mutable arguments, omitted parameter labels, and function overloading are used together to produce ambiguities, the compiler may raise an error
    func sum(v1: Int, v2: Int) -> Int { v1 + v2
    }
    func sum(_ v1: Int, _ v2: Int) -> Int {
        v1 + v2 }
    func sum(_ numbers: Int...) -> Int { var total = 0
        for number in numbers {
            total += number
        }
        return total
    }
    // error: ambiguous use of 'sum'
    sum(10, 20)
Copy the code

Function types

  • Every function has a type. Function types consist of formal parameter types and return value types
    func test() {} / / () - > Void or () - > () func sum (a: Int, b: Int) - > Int {} a + b / / (Int, Int) - > Int / / define variables var fn: (Int, Int) -> sum call: fn(2, 3)Copy the code

Function types as function parameters

For example,

func sum(v1: Int, v2: Int) -> Int { v1 + v2 } func difference(v1: Int, v2: Int) -> Int {v1 - v2} // use a function type (Int, Int) -> Int funcprintResult(_ mathFn: (Int, Int) -> Int, _ a: Int, _ b: Int) { print("Result: \(mathFn(a, b))"} // callprintResult(sum, 5, 2) // Result: 7
    printResult(difference, 5, 2) // Result: 3
Copy the code

A function whose return value is of type function

  • A Function whose return value is a Function type is called a higher-order Function.
func next(_ input: Int) -> Int { input + 1 } func previous(_ input: Int) -> Int { input - 1 } func forward(_ forward: Bool) -> (Int) -> Int { forward ? Next: previous} // Call forward(trueNext (3) forward(3)false(3) // 2 equivalent to call previous(3)Copy the code

Typealias alias

  • Used to alias a type
  typealias Date = (year: Int, month: Int, day: Int)
    func test(_ date: Date) {
        print(date.0)
        print(date.year)} // Call //test((2011, 9, 10))
Copy the code

Nested function

  • Define a function inside a function
    func forward(_ forward: Bool) -> (Int) -> Int { func next(_ input: Int) -> Int {
        input + 1 }
        func previous(_ input: Int) -> Int { input - 1
        }
        return forward ? next : previous
    }
    
    forward(true)(3) // 4
    forward(false/ / 2) (3)Copy the code

References:

Swift official source code

From beginner to proficient in Swift programming

More information, welcome to pay attention to the individual public number, not regularly share a variety of technical articles.