【问题标题】:Swift: understanding swift closureSwift:理解快速关闭
【发布时间】:2017-08-22 19:43:45
【问题描述】:

我试图快速理解关闭。我有以下快速实现:

func whereToGo (ahead:Bool) -> (Int) -> Int{
    func goAhead(input:Int) ->Int{
        return input + 1 }
    func goBack(input:Int) ->Int{
        return input - 1 }
    return ahead ? goAhead : goBack
}

var stepsToHome = -10
let goHome = whereToGo(ahead: stepsToHome < 0)

while stepsToHome != 0 {
    print("steps to home: \(abs(stepsToHome))")
    stepsToHome = goHome(stepsToHome)
}

实现的输出如下:

steps to home: 10
steps to home: 9
steps to home: 8
steps to home: 7
steps to home: 6
steps to home: 5
steps to home: 4
steps to home: 3
steps to home: 2
steps to home: 1

我的问题如下:

  1. 为什么只执行这个闭包:

    func goAhead(input:Int) ->Int{
        return input + 1 }
    
  2. 为什么这一行不采用变量值:

    提前返回? goAhead : 后退

非常感谢您帮助我了解快速关闭的工作原理。

【问题讨论】:

标签: swift closures


【解决方案1】:

这一行:

return ahead ? goAhead : goBack

是一种更简洁的说法:

if ahead == true {
    return goAhead
} else {
    return goBack
}

所以,既然您已将goHome 定义为:

let goHome = whereToGo(ahead: stepsToHome < 0)

只要stepsToHome 小于零,您将发送TRUE 作为ahead 参数。

附:不过,这确实与 Swift 闭包无关......

【讨论】:

    【解决方案2】:

    whereToGo 是一个基于输入参数ahead 返回另一个函数的函数。它返回一个接受Int 并返回另一个Int 的函数:(Int) -&gt; Int

    whereToGo 在其中声明了 2 个私有函数:goAheadgoBack,这些是它根据输入返回的函数之一。这两个函数被称为nested functions

    ahead ? goAhead : goBack 这一行使用ternary operator 决定返回哪个函数,当true 返回goAhead,否则返回goBack

    这里:

    var stepsToHome = -10
    let goHome = whereToGo(ahead: stepsToHome < 0)
    

    您正在调用whereToGo,并将其stepsToHome &lt; 0 作为输入参数,这是一个计算结果为true 的布尔值。 ==> goHome 现在指的是嵌套的 goAhead() 函数 ==> 它将被调用。

    而您正在迭代while stepsToHome != 0 ==> 条件stepsToHome &lt; 0 将始终为true ==> 当您调用goHome(stepsToHome) 时将始终调用goAhead() 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      相关资源
      最近更新 更多