Property Observers in Swift
Images by Chewy Pets Bringing us Together
Before we start
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 12.2, and Swift 5.3
Keywords and Terminology
Property Observers: Change and respond to changes in a property value. In Swift this is through didSet and willSet.
I’ve previously written an article about properties in Swift, which covers stored, computed and lazy properties.
This article on the other hand covers Property Observers, and it is about time that I did just that.
What is a Property Observer anyway?
Property observers observe and respond to changes in a property’s value. This can happen just before a value is changed with
willSet, or immediately after a value is set with
didSet. These property observers work on both
struct instances (no matter which you choose).
The use of Property Observers
If you are expecting a value to change, one might take the approach of requesting the current state of the value.
This would involve (perhaps) the use of a timer and perhaps a closure, and this is not a good approach for a well-coded App.
Much better would to be observe when changes are made, and then react accordingly. In steps Property Observers.
Imagine a game where we can score with a friend. Both Player 1 and Player 2 have a score and we want to log it with a program. This program is shown here:
This is then kicked off with an instance of the
Game class, and playerOne won the first game! This means that we will set the score to be 1, and then print out the score. We will do that by using the following three lines:
What if the property is changed to the same value?
The value of the property has been changed — even though it is to the same value. This means that both
didSet are called when the property is changed.
Let us write out this line:
So we have three lines that are then written to the console
I hope this article has been of help to you. I certainly use property observers all the time within my own code, and they are a brilliant tool for you to have avaliable in your quest to solve coding problems.
The Repo makes things rather easier to follow in this project, and I do recommend you download this project.
If you’ve any questions, comments or suggestions please hit me up on Twitter