Most people know that user defaults is a really simple way to store lightweight data and to keep track of user preferences. By using computed properties, you can streamline how you store items into user defaults.

Most apps have some places where settings are stored, usually small bits of information or a simple Bool value. It could be something like enabling/disabling haptic feedback, storing a name to greet your user, or keeping track of a logged in user id.

Let’s take the example of storing a retrieved user id. One method for doing it might be something like this:

This is mostly my opinion, but I believe that if something is just a standard value then why wrap it in a function? Personally, I prefer to simply make it a computed variable.

I think this has a few benefits over using the functions to set and retrieve the value.

First the value looks just like any other variable that we have, and it would look cleaner in a function call doFunctionWith(id: userId) looks much nicer to me than doFunctionWith(id: getIdFromDefaults()) . The logic to retrieve and set the variable is right there with the variable declaration. No need to look in two different places if you need to change logic of the code. The community making the language design choices for swift seems to prefer this look for values. Take for example UIColor.redColor() is now UIColor.redColor .

One of the items for me that makes this really powerful and really compelling is that we can use this to increase readability of things like preferences and toggles. Let’s imagine we have a way to choose what theme color our app uses. That might be easy to represent with an enum.

Now, you might be thinking…wait, why do it as an Int ? If we make this an Int, we’re going to get a few behaviors for free out of user defaults. First, when we save to UserDefaults, it is possible to Archive the color to UserDefaults using NSKeyedArchiver, but that might be more useful if we were trying to save a color generated by our user.

Second, with this, we can use the rawValue initializer of the Enum to allow us to have a default value. When UserDefaults tries to return an Int, if it can’t find it, then it returns 0 instead.

So, what would this look like when we put it into action in our code? Let’s imagine we have a tableview to select the theme color for our app. We might see some code that looks like this: