斯威夫特:理解快速关闭

use*_*482 -2 closures swift

我试图理解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)
}
Run Code Online (Sandbox Code Playgroud)

实现的输出如下:

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
Run Code Online (Sandbox Code Playgroud)

我的问题如下:

  1. 为什么只执行此闭包:

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

    回来?goAhead:goBack

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

Don*_*Mag 5

这一行:

return ahead ? goAhead : goBack
Run Code Online (Sandbox Code Playgroud)

是一种更紧凑的说法:

if ahead == true {
    return goAhead
} else {
    return goBack
}
Run Code Online (Sandbox Code Playgroud)

所以,既然你已经定义goHome为:

let goHome = whereToGo(ahead: stepsToHome < 0)
Run Code Online (Sandbox Code Playgroud)

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

PS这真的与Swift Closures无关......