函数的定义与调用
func sayHello(personName: String) -> String { let greeting = "Hello," + personName + "!" return greeting } print(sayHello("Anna")) // prints "Hello,Anna!" print(sayHello("Brian")) // prints "Hello,Brian!"
可变参数
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) // returns 3.0,which is the arithmetic mean of these five numbers arithmeticMean(3,8,19) // returns 10.0,which is the arithmetic mean of these three numbers
一个可变参数(variadic parameter)可以接受一个或多个值。
例如,一个叫做 numbers 的 Double... 型可变参数,在函数体内可以当做一个叫 numbers 的 Double[] 型的数组常量。
常量参数和变量参数
你可以通过指定一个或多个参数为变量参数,从而避免自己在函数中定义新的变量。
输入输出参数
func swapTwoInts(inout a: Int,inout b: Int) { let temporaryA = a a = b b = temporaryA } var someInt = 3 var anotherInt = 107 swapTwoInts(&someInt,b: &anotherInt) print("someInt is now \(someInt),and anotherInt is now \(anotherInt)") // prints "someInt is now 107,and anotherInt is now 3”
嵌套函数
func chooseStepFunction(backwards: Bool) -> (Int) -> Int { func stepForward(input: Int) -> Int { return input + 1 } func stepBackward(input: Int) -> Int { return input - 1 } return backwards ? stepBackward : stepForward } var currentValue = -4 let moveNearerToZero = chooseStepFunction(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!