Using Swift Property Observers To Clean Up Objects

Jimmy M Andersson
The Startup
Published in
4 min readJan 22, 2019

--

In the previous article, we glanced at how we could use the Delegate Pattern to separate our Views from our Controllers. Today we’re diving into the world of Property Observers, to see how we can use them to make our objects easier to deal with.

What is a Property Observer?

Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.

- Swift Programming Language Guide

The above explanation pretty much says it all. When declaring a Property Observer, we do so because we are interested in knowing when a certain value is changed. As the quote tells us, “change” does not necessarily mean that the actual value is changed. The idea is really to observe when a variable is written to, which can be a very useful thing. Apart from observing and notifying us of the change, we can also choose at what point in time we would like to be notified by choosing the willSet (before write) and/or didSet (after write) observers.

Let’s take a look at a few examples of how this could help us clean up our code and simplify for other developers that want to use our implementations. Let’s say that we are implementing a…

--

--

Jimmy M Andersson
The Startup

Software engineer with a passion for data and machine learning