Swift中的函数

1. 函数的参数与返回值

1.1 多重返回值函数

你可以用元组(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"

1.2 可选元组返回类型

如果函数返回的元组类型有可能整个元组都“没有值”,你可以使用可选的(optional)元组返回类型反映整个元组可以是nil的事实。

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

前面的minMax(array:)函数没有对传入的数组进行任何安全检查,如果array是个空数组,会触发一个运行时错误,使用可选元组返回类型,可以安全地处理这个问题。

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"

2.函数参数标签和参数名称

2.1 指定参数标签

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

from就是参数标签,hometown则是参数名称。

如果你希望忽略某个参数标签,可以使用_来代替一个标签。

2.2 默认参数值

func greet(person: String, from hometown: String = "Dream") -> String {
    return "Hello \(person)! Glad you could visit from \(hometown)"
}

greet(person: "John")

// 输出 "Hello John! Glad you could visit from Dream"

2.3 可变参数

一个可变参数可以接受零个或多个值,通过在变量类型名后面加入(...)的方式来定义可变参数。

可变参数的传入值在函数体中变为此类型的一个数组。

下面这个函数用来计算一组任意长度数字的算术平均数:

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

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

2.4 输入输出参数

函数参数默认是常量,试图在函数体中更改参数值将会导致编译错误。如果你想要一个函数可以修改参数的值,并且想要在这些修改在函数调用结束后仍然存在,那么就应该把这个参数定义为输入输出参数。

定义一个输入输出参数时,在参数定义前加inout关键字。一个输入输出参数有传入函数的值,这个值被函数修改,然后被传出函数,替换原来的值。

你只能传递变量给输入输出参数,常量或者字面量是不能被修改的。当传入的参数作为输入输出参数时,需要在参数名前加&符,表示这个值可以被函数修改。

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

func swapTowInts(_ a: inout Int, _ b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

var someInt = 3
var anotherInt = 107
swapTowInts(&someInt, &anotherInt)
print("someInt is now \(someInt), anotherInt is now \(anotherInt)")

// 输出 "someInt is now 107, anotherInt is now 3\n"

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

3.函数类型

每个函数都有特定的函数类型,函数的类型由函数的参数类型和返回类型组成。

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

func multipyTwoInts(_ a: Int, _ b: Int) -> Int {
    return a * b
}

上面这两个函数的类型是(Int, Int) -> Int,可以解读为“这个函数类型有两个Int型参数并返回一个Int型的值”。

func printHelloWordl() {
    print("Hello world!")
}

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

3.1 使用函数类型

在Swift中,使用函数类型就像使用其他类型一样。例如,你可以定义一个类型为函数的常量或变量,并将适当的函数赋值给它:

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

这段代码可以被解读为:“定义一个叫做mathFunciton的变量,类型是‘一个有两个Int型的参数并返回一个Int型的值的函数‘,并让这个新变量指向addTwoInts函数”。

print("Result: \(mathFunction(2, 3))")
// 输出 "Result: 5\n"

有相同匹配类型的不同函数可以被赋值给同一个变量:

mathFunction = multipyTwoInts
print("Result: \(mathFunction(2, 3))")
// 输出 "Result: 6\n"

就像其他类型一样,当赋值一个函数给常量或变量时,你可以让Swift来推断其函数类型:

let anotherMathFunction = addTwoInts
print("\(anotherMathFunction(1, 2))")
// 输出 "3\n"

3.2 函数类型作为参数类型

func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
    print("Result: \(mathFunction(a, b))")
}

printMathResult(addTwoInts, 3, 5)
// 打印 "Result: 8\n"

3.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
}

var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero 现在指向 stepBackward()

print("Counting to zero:")
// Counting to zero:
while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}

print("zero")

// 3...
// 2...
// 1...
// zero!

3.4 嵌套函数

目前为止你见到的所有函数都是全局函数,你也可以把函数定义在别的函数体中,称作嵌套函数。

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

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)

while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}
print("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容