|< When should you use a computed property or a stored property?||When should you use willSet rather than didSet? >|
Updated for Xcode 12.5
Swift’s property observers let us attach functionality to be run before or after a property is changed, using
didSet respectively. Most of the time property observers aren’t required, just nice to have – we could just update a property normally then call a function ourselves in code. So why bother? When would you actually use property observers?
The most important reason is convenience: using a property observer means your functionality will be executed whenever the property changes. Sure, you could use a function to do that, but would you remember? Always? In every place you change the property?
This is where the function approach goes sour: it’s on you to remember to call that function whenever the property changes, and if you forget then you’ll have mysterious bugs in your code. On the other hand, if you attach your functionality directly to the property using
didSet, it will always happen, and you’re transferring the work of ensuring that to Swift so your brain can focus on more interesting problems.
There is one place where using a property observer is a bad idea, and that’s if you put slow work in there. If you had a
User struct with an
age integer, you would expect that changing
age would take place virtually instantly – it’s just a number, after all. If you attach a
didSet property observer that does all sorts of slow work, then suddenly changing a single integer could take way longer than you expected, and it could cause all sorts of problems for you.
SPONSORED Emerge helps iOS devs write better, smaller apps by profiling binary size on each pull request and surfacing insights and suggestions. Companies using Emerge have reduced the size of their apps by up to 50% in just the first day. Built by a team with years of experience reducing app size at Airbnb.
Link copied to your pasteboard.