Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On which thread is a Swift property's didSet{} being executed?

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?

like image 462
funkenstrahlen Avatar asked Dec 02 '15 09:12

funkenstrahlen


People also ask

What does didSet mean in Swift?

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.

Is didSet called in init?

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.

What are property observers in Swift?

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.

What is newValue in Swift?

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.


1 Answers

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
    ...
like image 81
Martin R Avatar answered Sep 23 '22 19:09

Martin R