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):