我目前正在阅读 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)
您实际上是在以 currentValue
作为参数调用 stepBackward
。
要查看此操作的实际效果,请在创建 moveNearerToZero
之后立即添加此行:
println(moveNearerToZero(10)) // prints 9, since 10 is passed to stepBackward
关于ios - Swift 解释中函数类型作为返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25310379/