函数类型:参数类型和函数返回值共同组成
使用方法:
使用函数类型:将一个恰当的函数赋值给一个类型为函数的变量或常量
var mathFunction: (Int, Int) -> Int = addTwoInts
let anotherMathFunction = addTwoInts
//与mathFunction一样
使用:mathFunction(2, 3)
类型为函数的变量也可以像普通变量一样进行赋值
函数类型可以作为参数传给函数
func printMathresult(_ mathFunctions:(Int, Int) -> Int, _a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
printMathresult(addTwoInts, 3, 5)
函数类型可以作为返回值
func stepForward(_ input: Int) -> Int {
return input + 1
}
func stepBackward(_ input: Int) -> Int {
return input - 1
}e
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
return backward ? stepBackward : stepForward
}