This question came to my mind while reading the new language Swift, a new programming language Apple introduced in WWDC 2014, back in my old Objective-C day there are times when I need to write a custom setter/getter for my
It is very frustrating at first that I can’t do this anymore, then I ask myself what is the reason of using setter/getter and how I use it. Normally I use it when the change made on property affects other parts of the class and I usually write it this way.
- (void)setFoo:(NSString *)newValue
// some logic
_foo = newValue;
// the rest of the logic
It turns out in Swift I can still achieve this by implementing 2 new Property Observers
didSet so I can put “some logic” in
willSet and “the rest of the logic” in
didSet. I got 2 hidden benefits from this.
I can make sure my property is set properly.
There is no way I can go wrong when using property. when I set or get those
didSetalways enforce except where it shouldn’t (initializer). This replicated behavior we all do in Objective-c, use
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.
This is just a small example of how this new language syntax and restriction can reduce future runtime errors. The language is still young and surely needs improvements in many aspects, but I think it is worth trying if you are in doubt.
Other things I've written
- Data in SwiftUI, Part 2: Views as a function of data SwiftUI iOS Data
- Data in SwiftUI, Part 1: Data SwiftUI iOS Data
- UINavigationBar changes in iOS13 iOS13
- Adopting iOS Dark Mode Xcode iOS Dark Mode
- Modality changes in iOS13 iOS