ios - Swift 解释中函数类型作为返回类型

标签 ios swift

我目前正在阅读 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 返回并分配给 moveNearerToZeromoveNearerToZero 现在本质上是您之前定义的 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/

相关文章:

ios - NSString 操作。仅删除日期

Swift - 完成后重置/重启 SpeechSynthesizer

iphone - 如何将 "String-Calculation-Row"WITH 操作数转换为 double ?

ios webview 在不同选项卡/webview中打开链接

ios - 8.0 之前的 iOS 版本中布局边距相关的布局属性

使用自定义单元格快速显示警报

php - 是否可以将两个 JSON 对象从 PHP 发送到 Swift?

swift - 可选 var 未设置

ios - 解析JSON数据的JSON结构

ios - 如何向 UILabel 的固有内容大小添加填充?