Where is my getter/setter in Swift?

A missing Objective-C piece

Swift Objective-C

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 @property.

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 willSet and didSet so I can put “some logic” in willSet and “the rest of the logic” in didSet. I got 2 hidden benefits from this.

  1. I can make sure my property is set properly.

  2. There is no way I can go wrong when using property. when I set or get those willSet/didSet always enforce except where it shouldn’t (initializer). This replicated behavior we all do in Objective-c, use _var in init and [self var] elsewhere.

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 this article, you can subscribe to the weekly newsletter.

Every Friday, you’ll get a quick recap of all articles and tips posted on this site — entirely for free.

← Home