通常,函数以参数为输入时是按值传送的,输出返回的也是值。但是,使用inout关键字定义了参数,那就可以按引用传递参数,直接改变这个变量中存储的值。例如:
@H_403_3@import UIKit func swapValues(inout firstValue:Int,inout secondValue: Int){ let temp = firstValue firstValue = secondValue secondValue = temp } var swap1 = 2 var swap2 = 3 swapValues(&swap1,secondValue: &swap2) swap1//3 swap2//2swift中,函数可以用作变量,也就是说,在需要的情况下,函数可以返回一个函数——那么更神奇的就是,可以用函数创建新的函数,并在自己的代码中使用这个函数,栗子如下:
@H_403_3@import UIKit func createAdder(numberToAdd: Int) -> (Int) -> Int { func adder(number: Int) -> Int { return number + numberToAdd } return adder } var addTwo = createAdder(2) addTwo(5)//7函数还可以捕获一个值,并多次使用它。
@H_403_3@import UIKit func createIncrementor(incrementAmount: Int) -> () -> Int{ var amount = 0 func incrementor() ->Int{ amount += incrementAmount return amount } return incrementor } var incrementByTen = createIncrementor(10) incrementByTen()//10 incrementByTen()//20