2017-08-22 63 views
-1

我想理解快速關閉。我有以下迅速實施: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

我真的很感謝您的幫助,瞭解如何迅速關閉工作。

+0

您的問題更多地討論嵌套函數,這是閉包的特例。 –

+0

正如蘋果文檔所說的 - :嵌套函數是具有名稱的閉包,並且可以從其封閉函數捕獲值.https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html –

回答

4

這條線:

return ahead ? goAhead : goBack 

是說的更緊湊的方式:

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

所以,既然您已經定義goHome爲:

let goHome = whereToGo(ahead: stepsToHome < 0) 

只要stepsToHome是小於零,您發送TRUE作爲ahead參數河

P.S.這真的與Swift Closures無關......

3

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) 

要調用whereToGo給它stepsToHome < 0作爲輸入參數,它是計算結果爲true一個布爾值。 ==>goHome現在指的是嵌套的goAhead()函數==>它將被調用。

而且你迭代while stepsToHome != 0 ==>的條件stepsToHome < 0永遠是當你調用goHome(stepsToHome)true ==>goAhead()函數總是被調用。