函数的定义与调用
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”
嵌套函数
这章中你所见到的所有函数都叫全局函数(global functions),它们定义在全局域中。
你也可以把函数定义在别的函数体中,称作嵌套函数(nested functions)。
默认情况下,嵌套函数是对外界不可见的,但是可以被他们封闭函数(enclosing function)来调用。
默认情况下,嵌套函数是对外界不可见的,但是可以被他们封闭函数(enclosing function)来调用。
一个封闭函数也可以返回它的某一个嵌套函数,使得这个函数可以在其他域中被使用。
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!