In my previous article Class Initializers, I had mentioned property observers, and glossed over them a bit. Now we’ll discuss them in a bit more depth.
Why use a Property Observer?
Back in Objective-C, if you wanted to do any special handling for setting a property, you would have to override the setter, reimplement the actual value setting (that was originally done for you), and then add whatever you wanted to do besides that, like posting a notification of a change. Swift’s property observers save you from having to reimplement the setter in those cases.
Property Observers are somewhat similar to computed properties. You can read more about those in my previous article Computed Properties in Swift. For computed properties, you write custom code for the getter and setter. For property observers, you write custom code only for setting, for right before (willSet) and right after (didSet). The main purpose of Swift’s property observers is to watch for when a property is set. As such, property observers are only useful for variables (var properties), and cannot be written for constants (let properties).
[Read more…]