let moveNearerToZero = chooseStepFunction(currentValue > 0) // 根据参数返回 stepForward 或 stepBackward
println("Counting to zero:")
while currentValue != 0 {
println("(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
println("zero!")
// 3...
// 2...
// 1...
// zero!
别名
用多了会发现在一大串 ()-> 中又穿插各种 ()-> 是一个非常蛋疼的事情。我们可以用 typealias 定义函数别名,其功能和 OC 中的 typedef 以及 shell 中的 alias 的作用基本是一样的。举个例子来看下:
复制代码
import Foundation
typealias lotteryOutputHandler = (String, Int) -> String
// 如果没有 typealias 则需要这样:
// func luckyNumberForName(name: String, #lotteryHandler: (String, Int) -> String) -> String {
func luckyNumberForName(name: String, #lotteryHandler: lotteryOutputHandler) -> String {
let luckyNumber = Int(arc4random() % 100)
return lotteryHandler(name, luckyNumber)
}
luckyNumberForName("Mr. Roboto", lotteryHandler: {name, number in
return "(name)'s' lucky number is (number)"
})
// Mr. Roboto's lucky number is 33
嵌套
但是其实并不是所有的函数都需要暴露在外面的,有时候我们定义一个新函数只是为了封装一层,并不是为了复用。这时候可以把函数嵌套进去,比如前面这个例子:
复制代码
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 {
println("(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
println("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!
柯里化 (currying)








