I have defined a property in Swift like:
var foo : String {
didSet {
doSomething()
}
}
So everytime I set foo
like foo = "bar"
my didSet
will be executed.
However I can not find out on which thread didSet
is being executed.
For example what happens in this case:
dispatch_async(some_queue, { () -> Void in
self.foo = "bar"
})
This will cause the didSet
code to be executed. Will didSet
be run on some_queue
or always on the main_queue
?
In Swift, didSet and willSet methods act as property observers. willSet runs a piece of code right before a property changes. didSet runs a piece of code right after the property has changed.
willSet and didSet observers are not called when a property is first initialized. They are only called when the property's value is set outside of an initialization context.
Property observers observe and respond to changes in a property's value. Property observers are called every time a property's value is set, even if the new value is the same as the property's current value. You can add property observers in the following places: Stored properties that you define.
In willSet Swift provides your code with a special value called newValue that contains what the new property value is going to be, and in didSet you are given oldValue to represent the previous value.
The property observers willSet
and didSet
are directly called from within the setter method, immediately
before/after the new value is stored, so all this executes on the same thread.
You can verify that by setting a breakpoint in didSet
and inspecting
the stack backtrace, which would look like this:
* thread #2: tid = 0x4df3, 0x000000010024f9eb swtest2`swtest2.foo.didset : Swift.String(oldValue="foo") + 27 at main.swift:6, queue = 'myQueue', stop reason = breakpoint 1.1 * frame #0: 0x000000010024f9eb swtest2`swtest2.foo.didset : Swift.String(oldValue="foo") + 27 at main.swift:6 frame #1: 0x000000010024fb91 swtest2`swtest2.foo.setter : Swift.String(newValue="bar") + 177 at main.swift:4 frame #2: 0x000000010024fe3a swtest2`swtest2.(closure #1) + 42 at main.swift:13 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With