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

后端 未结 2 1599
無奈伤痛
無奈伤痛 2021-01-21 12:17

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         


        
相关标签:
2条回答
  • 2021-01-21 12:59

    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)
    })
    
    0 讨论(0)
  • 2021-01-21 13:21

    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)
        })
    
    0 讨论(0)
提交回复
热议问题