Computed Variables vs Property Observers — Disambiguation

So, when I first started programming in Swift, one of the things that I found confusing is Computed Properties {get set} and Property Observers { willSet didSet }. Visually, both look very similar and both can trigger side effects in other areas of the code or change things when the values are set to them.

I want to spend a couple of minutes explaining both and their similarities and differences. Both can be incredibly useful tools for streamlining your code and making it less verbose and more modular.

Computed Properties

Computed properties don’t have any storage value. Much like quantum theory (I think? I’m not a quantum physicist), their value is not known until they are interacted with. Instead of a holding a value, they hold a small closure that generates the value dynamically at the time that it is accessed. Computed properties can be read only { get } or can be read-write { get set } properties.

I’m a really big fan of using computed properties with User Defaults, and there’s lots of other compelling cases for what you can do with this, like this:

Another case recently where I ended up using this was to deal with geofencing. I was using an api that returned latitude, longitude , and radius_mile. The only problem was that apple’s CLCircularRegion expects a distance in meters! This was an obvious case for using a computed variable:

Property Observers

Property observers are “regular” variables, but with a twist. Any time that their value is set (after initialization), they give a chance for code to be run in response to an observed change. They look like this:

This looks very similar to the computed variables, but it’s important to remember that items or name in the example above always has a value, which is not dynamically generated every time it is accessed.

Property observers are great when you need to perform a certain action every time something is updated, especially when it can be updated from multiple different points in your code.

I’ve personally found that it works well when creating your own delegate pattern. For example, consider the case of a toy I’m basing on one that I enjoyed in my childhood (but have hopefully altered enough so that I don’t get sued =) ):

Notice how startNewGame() and setNewRandomAction() both modify current action. Instead of placing the logic for the delegate callback in both places, it’s cleaner and simpler to place it in the property observer on the currentAction variable.

You can check it out by combining the snippet above with this code below in a playground (or click here for the full example):

Hopefully this article can help to explain some of the differences between these two quite different but very similar looking types of variables!

Like what you read? Give Joe Spadafora a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.