2017-04-10 70 views
1
func sortFunc (array: [Int], closure: (Int?, Int) -> Bool) -> Int { 
    var tempVar: Int? = nil 
     for value in array { 
      if closure (tempVar, value) { 
       tempVar = value 
      } 
     } 

    return tempVar! 
} 

在這段代碼我不明白這一點:如果在那裏工作?

if closure (tempVar, value) { 
    tempVar = value 
} 

你能解釋一下封閉(TempVar的,值)意味着什麼? 我試圖在文檔中查找信息,但沒有任何信息可以幫助我。

+1

請閱讀[閉包](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID94) (Swift編程語言)一章(https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/index.html#//apple_ref/doc/uid/TP40014097-CH3-ID0) – rmaddy

回答

1

讓我們來分析一下。縱觀方法簽名,你可以看到closure定義:

func sortFunc (array: [Int], closure: (Int?, Int) -> Bool) -> Int 

這意味着,有一個用於功能sortFunc其中必須有兩個參數,一個Int?Int命名爲closure參數,返回一個Bool ean value。

那麼這甚至意味着什麼?

這意味着我們將函數改爲sortFunc作爲參數。這方面的一個例子是這樣的:

func myFunction(_ temporaryValue: Int?, value: Int) { 
    // return a boolean value 
    return temporaryValue != nil 
} 

當你調用if closure(tempVar, value)它基於該功能的效果評估通過提供的tempVarvalue參數的函數,並返回一個布爾值(真/假) 。

+0

謝謝你的幫助! – MoXyLe

1

closure是一個代碼塊採用兩個參數,一個Int?和一個Int,並返回一個Bool

它可以像一個函數調用,並會返回一個值。

當你這樣做if closure(tempVar, value),你用這兩個參數調用這段代碼,所以它會返回一個布爾值。

+0

謝謝你的幫助! – MoXyLe