2017-02-10 105 views
0

我有這種方法,它接受一個標誌,並根據它更新UI。Swift默認參數使用緩存值

func foo(flag: Bool = Reachability.isReachable) { 
    if (flag) { 
     // Show an alert 
    } else { 
     // Do nothing 
    } 
} 

使用默認參數的布爾實際上是可達性的可達性。

一旦網絡連接關閉,標誌的期望值爲false,但其始終爲true。如果我直接檢查它,而不使用if Reachability.reachable等默認參數,則會顯示警報。

使用動態更改的默認參數是錯誤的嗎?

回答

0

我想找到一些官方文檔,但我不能。 Swift默認參數值不是動態綁定的。看到這個帖子

https://airspeedvelocity.net/2014/06/12/default-parameters-in-swift-are-statically-bound/

編輯:

嗯,我錯了,看起來它是動態的。你可以用這個操場測試:

//: Playground - noun: a place where people can play 

import Cocoa 

func myFunction(date: Date = Date()) { 
    print("Using date \(date)") 
} 

myFunction() 
sleep(3) 
myFunction() 

你會看到等待後3秒之日起變化,所以它的第二呼叫作出新的Date ......也許有你的可達性代碼中的錯誤?