UserDefaults extension for Swifty variables

For quite some time now I’ve been using a UserDefaults extension class to make reading and writing user information much more manageable. In “old” times, writing a value to UserDefaults (or NSUserDefaults) was done like so:

Now there’s nothing wrong with doing this, it works fine. But who wants “fine”? We’re Swift developers and we can make this way more Swifty! In a real world application, chances are good you’ll want to access the “name” key value in various points throughout your app. Given our current solution, we’ll end up with a lot of repetition.

Enter UserDefaults extension!

Adding a variable “name” as an extension to UserDefaults makes this problem disappear, whilst simultaneously giving us extra functionality for free.

This is great. At our call site we can now reference the “name” property directly via, without having to input the “name” String value. But let’s take this one step further and remove the optional conformance on our variable. UserDefaults.standard.string(...) by default returns an optional String. Combined with the nil coalescing operator, we can make our “name” variable non optional:

Note: You may not always want this, and in most cases you’d probably prefer to keep “name” as optional, this is purely for demonstration purposes.

One final example of why I do this in my apps. Say we are reading/writing a custom data type not offered by UserDefaults. Say we are storing a Dictionary that uses a String as it’s key and a Date as it’s value. With our new extension class, we can do this easily:

Referencing this value at the call site throughout our entire app now looks like UserDefaults.stringDateDictionary. I think we can all agree this is now much more readable, much more maintainable, and much more Swifty!


Leave a comment