How to capture a variable's current value for a block

a 夏天 提交于 2019-12-20 02:56:29

问题


Is there a way to save the current value of a varible for later usage in a block?

For example, for this Playground code:

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()

Is there a way to save the current value of i for dispatch_after in a way that I get the output i: 0 instead of i: 3?


回答1:


You can bind an arbitrary expression to a named value in a capture list, the expression is evaluated when the closure is created. In your case you would bind self.i:

dispatch_after(dispatchTime, dispatch_get_main_queue(), { [i = self.i] in
    self.test(i)
})



回答2:


Since you're referencing i through a captured self, you will get whatever the value is at dispatch time. If you want to capture the value as it is at the beginning of the function, you'll need to get a local copy before changing it.

    let x = self.i
    dispatch_after(dispatchTime, dispatch_get_main_queue(), {
        self.test(x)
    })


来源:https://stackoverflow.com/questions/37300970/how-to-capture-a-variables-current-value-for-a-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!