swift语言点评五-Function

2022-12-09,,,

一、函数类型

Every function in Swift has a type, consisting of the function’s parameter types and return type.

Function Types

Every function has a specific function type, made up of the parameter types and the return type of the function.

For example:

    func addTwoInts(_ a: Int, _ b: Int) -> Int {
    return a + b
    }
    func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
    return a * b
    }

This example defines two simple mathematical functions called addTwoInts and multiplyTwoInts. These functions each take two Int values, and return an Int value, which is the result of performing an appropriate mathematical operation.

The type of both of these functions is (Int, Int) -> Int. This can be read as:

“A function that has two parameters, both of type Int, and that returns a value of type Int.”

Using Function Types

You use function types just like any other types in Swift. For example, you can define a constant or variable to be of a function type and assign an appropriate function to that variable:

    var mathFunction: (Int, Int) -> Int = addTwoInts

This can be read as:

“Define a variable called mathFunction, which has a type of ‘a function that takes two Int values, and returns an Int value.’ Set this new variable to refer to the function called addTwoInts.”

Function Types as Parameter Types

Here’s an example to print the results of the math functions from above:

    func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
    print("Result: \(mathFunction(a, b))")
    }
    printMathResult(addTwoInts, 3, 5)
    // Prints "Result: 8"

Function Types as Return Types

右侧结合律

Function Argument Labels and Parameter Names

Each function parameter has both an argument label and a parameter name. The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label.

Specifying Argument Labels

    func greet(person: String, from hometown: String) -> String {
    return "Hello \(person)! Glad you could visit from \(hometown)."
    }
    print(greet(person: "Bill", from: "Cupertino"))

关键字:

In-Out Parameters

Function parameters are constants by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error.

Optional Tuple Return Types

An optional tuple type such as (Int, Int)? is different from a tuple that contains optional types such as (Int?, Int?). With an optional tuple type, the entire tuple is optional, not just each individual value within the tuple.

func minMax(array: [Int]) -> (min: Int, max: Int)?

返回值需要判断

swift语言点评五-Function的相关教程结束。

《swift语言点评五-Function.doc》

下载本文的Word格式文档,以方便收藏与打印。