simpleBob simpleBob - 1 year ago 47
Swift Question

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

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(), {
i = 3

func test(i: Int)
print("i: \(i)")

let a = testClass()

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

Answer Source

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