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

You will be expected to be aware how to either make a Single View Application in Swift or use a Playground

Property Observers: Change and respond to changes in a property value. In Swift this is through didSet and willSet.

This article

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.

I’ve prepared a Repo that can help you see the code that is avaliable in this article. I’ve created a guide on how to download the repo from GitHub and I think that should assist some out there!

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 class and struct instances (no matter which you choose).

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:

The answer

The value of the property has been changed — even though it is to the same value. This means that both willSet and 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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store