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.
Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.
If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.Become a patron Tweet Share