Better Getters & Setters with observers in Swift

Create Getters & Setters

Better Getters & Setters with observers in Swift… Wow, try to say this three times fast without twisting your tongue.

Ok, whatever.

Using Getter/Setter methods in Swift is pretty straight forward and looks familiar for if you have experience in other languages like Java, C# or ActionScript etc. But an interesting thing is Swifts observer functionality that gives you more control over these methods. But first we look at the standard way we use getters/setters in other programming languages.

In case you ask yourself were the newValue is coming from: The newValue is set by default if no parameter is defined by the Setter method.

[adinserter block=”10″]

Property observers

Ok, and now the fancy new stuff: Observers allow you to execute code when a value is set via setter method. For this there are the keywords: willSet and didSet. In the example below the Setter is printing a message when it is about to set a new value using the willSet statement. Further the Setter checks if the new value is greater 100 and corrects the value if this is the case. This is done by using the didSet statement.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.