Self-mutate Swift struct in background thread

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

        // Start some background operation
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {

            // Mutate self upon background task completion
            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?

// Ew
var myThing = Thing()
myThing.operation {
    (mutatedThing) in
    myThing = mutatedThing
    println(myThing.something)
}
+4
source share
2 answers

, .

, .

, , , , , , , , , .

, , - .

, , , , - , ( ) , .

, . , .

+5

, , , .

, , , . , . " " - , , , . , , , , " ", . .

, . , !

0

Source: https://habr.com/ru/post/1606197/


All Articles