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

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.

Photo by William Hook on Unsplash

Save Data

Writing data to UserDefaults is as simple as defining UserDefaults then setting an object for a key.


Get Data

Getting the saved data from the UserDefaults is just as easy as saving it.


Reading/Writing Both Even Easier

Combining both the saving and retrieving in the get and set on a variable makes the process feel built in. To get the saved value just call the variable as you normally would and to save it back to UserDefaults just set your variable to the new value.


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.

Like what you read? Give Zach Miles a round of applause.

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