斯威夫特:理解快速关闭

时间:2017-08-22 19:43:46

标签: swift closures

我试图理解swift中的闭包。我有以下快速实现:

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:goBack

  3. 我非常感谢你的帮助,以了解如何快速关闭工作。

2 个答案:

答案 0 :(得分:5)

这一行:

runat="server"

是一种更紧凑的说法:

return ahead ? goAhead : goBack

因此,您已将if ahead == true { return goAhead } else { return goBack } 定义为:

goHome

只要let goHome = whereToGo(ahead: stepsToHome < 0) 小于零,您就会发送TRUE作为stepsToHome参数。

P.S。这真的与Swift Closures无关......

答案 1 :(得分:4)

whereToGo是一个函数,它根据输入参数ahead返回另一个函数。它返回一个函数,该函数接受Int并返回另一个Int(Int) -> Int

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

这一行ahead ? goAhead : goBack使用ternary operator来决定返回哪个函数,当true返回goAhead时,它会返回goBack

下面:

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

您正在调用whereToGostepsToHome < 0作为输入参数,这是一个评估为true的布尔值。 ==&GT; goHome现在指的是嵌套的goAhead()函数==&gt;它将被调用。

您正在迭代while stepsToHome != 0 ==&gt;条件stepsToHome < 0始终为true ==&gt;当您致电goAhead()时,将始终调用goHome(stepsToHome)函数。

相关问题