Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.


Swift Gotcha: Unexpected observer behaviour for inout arguments

I recently ran into an observer problem: it was being called without updates to the associated variable.

Since I was using the associated variable as an inout argument, that was my first suspect. So I wrote a little test in playground to investigate this:

So, ... indeed. The observer of 'str' is called even though the property is not updated in "testDidSetObserver". Note that even when the if statement is removed from the function the observer is still called. It seems that using a property in an inout argument will always trigger the property observers after the function is finished.

I also ran a test that prints the value of "countDidSet" inside the function, and the count is 0 inside the function. Thus the observer is indeed triggered after the function finishes, whether the property is accessed or not.

So observers and inout arguments don't mix well.

PS: I also ran the test for the willSet observer, same results.

Note: As of Swift 2.2 this behaviour is now documented in the manual with a little explanation as to why.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment