我想理解快速關閉。我有以下迅速實施: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
我的問題有以下幾點:
爲什麼只執行該關閉:
func goAhead(input:Int) ->Int{ return input + 1 }
爲什麼在這條線上沒有采取變量值:
提前回來? goAhead:goBack
我真的很感謝您的幫助,瞭解如何迅速關閉工作。
您的問題更多地討論嵌套函數,這是閉包的特例。 –
正如蘋果文檔所說的 - :嵌套函數是具有名稱的閉包,並且可以從其封閉函數捕獲值.https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html –