我有一個inout
放慢參數的函數:enabled: Bool
我引用的對象(我知道inout
在技術上不是參考...)和使用該方法是設置一個存儲的屬性上UIViewController
var enabled = false
INOUT變量設置在UIAlertAction閉合不變更值
我有多個布爾值觸發不同的事情,我想用一種方法來設置它們。
因此,我調用該方法:
self.determineEnabled(&self.enabled)
下面是代碼,我已經用註釋來解釋發生了什麼
代碼:
func determineEnabled(inout enabled: Bool) {
if enabled == false {
enabled = true
//self.enabled equals true now. This works. Its not in a closure...
} else {
let delete = UIAlertAction(title: "Disable", style: .Destructive, handler: { (action) -> Void in
enabled = false
print(self.enabled)
//This doesn't work. the inout variable equals FALSE
//self.enabled equals true
//If I set self.enabled = false.. Then it works, but I'm using a method because my app could have dozens of these enabled bools on this view controller.
let alertController = UIAlertController(title: "Change Bool", message: "", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(delete)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
我的應用程序是顯然比這段代碼更復雜,但是我可以驗證這個問題存在於代碼的這個塊中。
我會說實話,我不完全理解閉包,就像我想..
但如果我可以使用self.enabled
正確地改變啓用的價值,什麼是停止從迅速變化設置inout啓用變量?
UPDATE:
下面是從文檔的鏈接,特別提到我的問題: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/doc/uid/TP40014097-CH34-ID545
「沒有複製出在閉合或嵌套函數結束這意味着,如果一個封閉在函數返回後被調用,任何閉包對入出參數的改變都不會被複制回原來的。「在話題
斯威夫特進化:
我不認爲這是可能給出這樣的回答:http://stackoverflow.com/a/28286993/4096655我實際上也先前問?對SO有關的方法是總是可用的執行長蓋和框架是,但參數是現在不變,http://stackoverflow.com/a/34915207/4096655 –