Suppose we have a self-mutable structure that must happen as part of a background operation:
struct Thing {
var something = 0
mutating func operation(block: () -> Void) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
self.something += 1
block()
}
}
}
Now when I use this structure in context:
var myThing = Thing()
myThing.operation {
println(myThing.something)
}
printlngives me 0as if he myThingnever mutated. Printing self.somethingout dispatch_asyncobviously gives 1.
How can I get around this problem, it is advisable without having to transfer the updated structure selfin the competition block operationand redefine the original variable in the main context?
var myThing = Thing()
myThing.operation {
(mutatedThing) in
myThing = mutatedThing
println(myThing.something)
}
source
share