//: Playground - noun: a place where people can play
import UIKit
//每一个函数都有特定的函数类型,可以充当参数类型和函数的返回类型。
func addTwoInts(a: Int, b: Int) -> Int {
return a + b
}
func multiplyTwoInts(a: Int, b: Int) -> Int {
return a * b
}
//使用函数类型
//在 swift 中您可以像任何其他类型一样的使用函数类型。例如,你可以定义一个常量或变量为一个函数类型,并指定适 当的函数给该变量:
var mathFunction: (Int, Int) -> Int = addTwoInts
mathFunction(2, 4)
//不同的函数相同的匹配类型可以分配给相同的变量,也同样的适用于非函数性类型:
mathFunction = multiplyTwoInts
mathFunction(2, 4)
//与其他类型一样,你可以把它迅速推断成函数类型当你为常量或变量分配一个函数时:
let anotherMathFunction = addTwoInts
anotherMathFunction(5,7)
//函数类型的参数
//您可以使用一个函数类型,如(Int, Int)->Int 作为另一个函数的参数类型。
func printMathResult(mathFun: (Int, Int) -> Int, a: Int, b: Int) {
println("Result:\(mathFun(a, b))")
}
printMathResult(addTwoInts, 5, 10)
//您可以使用一个函数类型作为另一个函数的返回类型。
func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backwards: Bool) -> (Int)-> Int {
return backwards ? stepBackward : stepForward
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0)
//moveNearerToZero(9)
while currentValue != 0 {
println("\(currentValue)")
currentValue = moveNearerToZero(currentValue)
}