[英]How to capture a variable's current value for a block
有沒有辦法保存變量的當前值以供以后在塊中使用?
例如,對於此Playground代碼:
import UIKit
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
class testClass {
var i = 0
func test() {
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC)) * 5)
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
self.test(self.i)
})
i = 3
}
func test(i: Int)
{
print("i: \(i)")
}
}
let a = testClass()
a.test()
有沒有辦法以我得到輸出i: 0
而不是i: 3
的方式為dispatch_after
保存i
的當前值?
您可以將任意表達式綁定到捕獲列表中的命名值,在創建閉包時計算表達式。 在你的情況下,你會綁定self.i
:
dispatch_after(dispatchTime, dispatch_get_main_queue(), { [i = self.i] in
self.test(i)
})
由於您通過捕獲的self
引用i
,因此您將在發送時獲得任何價值。 如果要捕獲函數開頭的值,則需要在更改之前獲取本地副本。
let x = self.i
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
self.test(x)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.