Storing Swift objects in UserDefaults using Get/Set on a Variable

Zach Miles
Mar 5, 2018 · 2 min read

For quickly and easily storing variables in your Swift application, UserDefaults is a generally quick and easy way to go. It can be used for just about anything from checking if it is the first time your app has been opened to storing preferences. UserDefaults can be a very simple solution to keeping most data including the types: Object, URL, Array, Dictionary, String, StringArray, Data, Bool, Integer, Float, Double and Dictionary Representation.

The documentation for UserDefaults is located here.

Below is my quick and easy method for storing and retrieving data using the getter and setter methods on variables in Swift 4.

Save Data

Get Data

Reading/Writing Both Even Easier

And that’s it. Just use your var as you normally would and it will be retrieved from UserDefaults every time you call it and will be saved again every time you set a new value!

Have another question? Looking for more semi-useful information? Hit me up on Twitter or my website.

Zach Miles

Written by

designer. developer. all around  nerd. usually the earliest adopter. full time creative. going places.