我目前正在研究Apple的《 Swift编程手册》,书中有使用函数类型作为返回类型的示例。
// Using a function type as the return type of another function
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)
println("Counting to zero:")
// Counting to zero:
while currentValue != 0 {
println("\(currentValue)...")
currentValue = moveNearerToZero(currentValue)
}
println("zero!")
据我了解
let moveNearerToZero = chooseStepFunction(currentValue > 0)
调用
chooseStepFunction
并传递“true”,因为3>0。此外,我了解如何评估以下内容:return backwards ? stepBackward : stepForward
我的问题是函数
stepBackward
如何知道将currentValue
用作其输入参数?我知道发生了什么,但我不知道发生的方式或原因... 最佳答案
stepBackward
函数不知道在此行中使用currentValue
-在这一点上它根本没有被调用:
return backwards ? stepBackward : stepForward
而是从
stepBackward
返回对chooseStepFunction
的引用,并将其分配给moveNearerToZero
。现在moveNearerToZero
实际上是您先前定义的stepBackward
函数的另一个名称,因此在循环中发生这种情况时:currentValue = moveNearerToZero(currentValue)
您实际上是使用
stepBackward
作为参数调用currentValue
。要查看实际效果,请在创建
moveNearerToZero
之后立即添加以下行:println(moveNearerToZero(10)) // prints 9, since 10 is passed to stepBackward