美文网首页
Swift:函数

Swift:函数

作者: 伯wen | 来源:发表于2018-07-09 10:53 被阅读5次

    一、函数定义与调用

    • 语法
    func 函数名() -> 返回值 {
        函数体
        return 返回值
    }
    

    二、函数参数与返回值

    • 函数参数与返回值在Swift中非常的灵活, 你可以定义任何类型的函数,包括从只带一个未名参数的简单函数到复杂的带有表达性参数名和不同参数选项的复杂函数。
    1、无参无返回值函数
    func say() {
        print("hello world!")
    }
    
    2、无参有返回值函数
    func say() -> String {
        return "hello world!"
    }
    
    3、有参无返回值
    func sum(x: Int, y: Int) {
        print(x + y)
    }
    
    4、有参有返回值
    func sum(x: Int, y: Int) -> Int {
        return x + y
    }
    

    注意
    没有定义返回类型的函数会返回一个特殊的 Void 值。它其实是一个空的元组,没有任何元素,可以写成()

    • 被调用时,一个函数的返回值可以被忽略:
    func printAndCount(string: String) -> Int {
        print(string)
        return string.count
    }
    func printWithoutCounting(string: String) {
        let _ = printAndCount(string: string)
    }
    printAndCount(string: "hello, world")
    // 打印 "hello, world" 并且返回值 12
    printWithoutCounting(string: "hello, world")
    // 打印 "hello, world" 但是没有返回任何值
    
    5、多重返回值函数
    • 可以用元组(tuple)类型让多个值作为一个复合值从函数中返回。
    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("min is \(bounds.min) and max is \(bounds.max)")
    // 打印 "min is -6 and max is 109"
    
    6、可选元组返回类型

    注意
    可选元组类型如 (Int, Int)? 与元组包含可选类型如 (Int?, Int?) 是不同的。可选的元组类型,整个元组是可选的,而不只是元组中的每个元素值。

    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)
    }
    
    • 你可以使用可选绑定来检查 minMax(array:) 函数返回的是一个存在的元组值还是 nil
    if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) {
        print("min is \(bounds.min) and max is \(bounds.max)")
    }
    // 打印 "min is -6 and max is 109"
    

    三、函数参数标签和参数名称

    每个函数参数都有一个参数标签(argument label)以及一个参数名称(parameter name)。
    参数标签在调用函数的时候使用;
    调用的时候需要将函数的参数标签写在对应的参数前面。
    参数名称在函数的实现中使用。
    默认情况下,函数参数使用参数名称来作为它们的参数标签。
    
    1、指定参数标签
    • 语法
    func someFunction(argumentLabel parameterName: Int) {
        // 在函数体内,parameterName 代表参数值
    }
    
    • 下面是 greet(person:) 函数,接收一个人的名字和他的家乡,并且返回一句问候:
    func greet(person: String, from hometown: String) -> String {
        return "Hello \(person)!  Glad you could visit from \(hometown)."
    }
    print(greet(person: "Bill", from: "Cupertino"))
    // 打印 "Hello Bill!  Glad you could visit from Cupertino."
    
    • 参数标签的使用能够让一个函数在调用时更有表达力,更类似自然语言,并且仍保持了函数内部的可读性以及清晰的意图。
    2、忽略参数标签
    • 如果你不希望为某个参数添加一个标签,可以使用一个下划线(_)来代替一个明确的参数标签。
    func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
         // 在函数体内,firstParameterName 和 secondParameterName 代表参数中的第一个和第二个参数值
    }
    someFunction(1, secondParameterName: 2)
    
    • 如果一个参数有一个标签,那么在调用的时候必须使用标签来标记这个参数。
    3、默认参数值
    • 你可以在函数体中通过给参数赋值来为任意一个参数定义默认值。当默认值被定义后,调用这个函数时可以忽略这个参数。
    func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
        // 如果你在调用时候不传第二个参数,parameterWithDefault 会值为 12 传入到函数体中。
    }
    someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault = 6
    someFunction(parameterWithoutDefault: 4) // parameterWithDefault = 12
    
    • 将不带有默认值的参数放在函数参数列表的最前。
    • 一般来说,没有默认值的参数更加的重要,将不带默认值的参数放在最前保证在函数调用时,非默认参数的顺序是一致的,同时也使得相同的函数在不同情况下调用时显得更为清晰。
    4、可变参数
    • 一个可变参数(variadic parameter)可以接受零个或多个值。
    • 函数调用时,你可以用可变参数来指定函数参数可以被传入不确定数量的输入值。
    • 通过在变量类型名后面加入(...)的方式来定义可变参数。
    func arithmeticMean(_ numbers: Double...) -> Double {
        var total: Double = 0
        for number in numbers {
            total += number
        }
        return total / Double(numbers.count)
    }
    arithmeticMean(1, 2, 3, 4, 5)
    // 返回 3.0, 是这 5 个数的平均数。
    arithmeticMean(3, 8.25, 18.75)
    // 返回 10.0, 是这 3 个数的平均数。
    

    注意
    一个函数最多只能拥有一个可变参数。

    5、输入输出参数
    * 函数参数默认是常量。
    * 试图在函数体中更改参数值将会导致编译错误。
    * 这意味着你不能错误地更改参数值。
    
    * 如果你想要一个函数可以修改参数的值,
    * 并且想要在这些修改在函数调用结束后仍然存在,
    * 那么就应该把这个参数定义为输入输出参数
    
    * 定义一个输入输出参数时,在参数定义前加 `inout` 关键字。
    
    * 你只能传递变量给输入输出参数。
    * 你不能传入常量或者字面量,因为这些量是不能被修改的。
    
    * 当传入的参数作为输入输出参数时,
    * 需要在参数名前加 & 符,
    * 表示这个值可* 以被函数修改。
    

    注意
    输入输出参数不能有默认值,而且可变参数不能用 inout 标记。

    • 下例中,swapTwoInts(_:_:) 函数有两个分别叫做 a 和 b 的输入输出参数
    func swapTwoInts(_ a: inout Int, _ b: inout Int) {
        let temporaryA = a
        a = b
        b = temporaryA
    }
    var someInt = 3
    var anotherInt = 107
    swapTwoInts(&someInt, &anotherInt)
    print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
    // 打印 "someInt is now 107, and anotherInt is now 3"
    

    注意
    输入输出参数和返回值是不一样的。上面的 swapTwoInts 函数并没有定义任何返回值,但仍然修改了 someIntanotherInt 的值。输入输出参数是函数对函数体外产生影响的另一种方式。

    四、函数类型

    • 每个函数都有种特定的函数类型,函数的类型由函数的参数类型和返回类型组成。
    • 例如下面两个函数的类型是 (Int, Int) -> Int
    func addTwoInts(_ a: Int, _ b: Int) -> Int {
        return a + b
    }
    func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
        return a * b
    }
    
    • 下面是另一个例子,一个没有参数,也没有返回值的函数:
    func printHelloWorld() {
        print("hello, world")
    }
    

    这个函数的类型是:() -> Void,或者叫“没有参数,并返回 Void 类型的函数”。

    1、使用函数类型
    • 在 Swift 中,使用函数类型就像使用其他类型一样。例如,你可以定义一个类型为函数的常量或变量,并将适当的函数赋值给它:
    var mathFunction: (Int, Int) -> Int = addTwoInts
    
    • 现在,你可以用 mathFunction 来调用被赋值的函数了:
    print("Result: \(mathFunction(2, 3))")
    // Prints "Result: 5"
    
    • 有相同匹配类型的不同函数可以被赋值给同一个变量,就像非函数类型的变量一样:
    mathFunction = multiplyTwoInts
    print("Result: \(mathFunction(2, 3))")
    // Prints "Result: 6"
    
    • 就像其他类型一样,当赋值一个函数给常量或变量时,你可以让 Swift 来推断其函数类型:
    let anotherMathFunction = addTwoInts
    // anotherMathFunction 被推断为 (Int, Int) -> Int 类型
    
    2、函数类型作为参数类型
    • 你可以用 (Int, Int) -> Int 这样的函数类型作为另一个函数的参数类型
    func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
        print("Result: \(mathFunction(a, b))")
    }
    printMathResult(addTwoInts, 3, 5)
    // 打印 "Result: 8"
    
    3、函数类型作为返回类型
    • 你可以用函数类型作为另一个函数的返回类型。你需要做的是在返回箭头(->)后写一个完整的函数类型。
    func stepForward(_ input: Int) -> Int {
        return input + 1
    }
    func stepBackward(_ input: Int) -> Int {
        return input - 1
    }
    
    func chooseStepFunction(backward: Bool) -> (Int) -> Int {
        return backward ? stepBackward : stepForward
    }
    
    • 你现在可以用chooseStepFunction(backward:)来获得两个函数其中的一个:
    var currentValue = 3
    let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
    // moveNearerToZero 现在指向 stepBackward() 函数。
    
    • 现在,moveNearerToZero 指向了正确的函数,它可以被用来数到零:
    print("Counting to zero:")
    // Counting to zero:
    while currentValue != 0 {
        print("\(currentValue)... ")
        currentValue = moveNearerToZero(currentValue)
    }
    print("zero!")
    // 3...
    // 2...
    // 1...
    // zero!
    

    五、嵌套函数

    • 到目前为止本章中你所见到的所有函数都叫全局函数,它们定义在全局域中。你也可以把函数定义在别的函数体中,称作 嵌套函数。

    • 默认情况下,嵌套函数是对外界不可见的,但是可以被它们的外围函数调用。一个外围函数也可以返回它的某一个嵌套函数,使得这个函数可以在其他域中被使用。

    func chooseStepFunction(backward: Bool) -> (Int) -> Int {
        func stepForward(input: Int) -> Int { return input + 1 }
        func stepBackward(input: Int) -> Int { return input - 1 }
        return backward ? stepBackward : stepForward
    }
    var currentValue = -4
    let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
    // moveNearerToZero now refers to the nested stepForward() function
    while currentValue != 0 {
        print("\(currentValue)... ")
        currentValue = moveNearerToZero(currentValue)
    }
    print("zero!")
    // -4...
    // -3...
    // -2...
    // -1...
    // zero!
    

    相关文章

      网友评论

          本文标题:Swift:函数

          本文链接:https://www.haomeiwen.com/subject/nbpauftx.html