Using and Testing User Defaults in Swift

Knowing when to use it is important!

Steven Curtis
4 min readFeb 1, 2023
Photo by Patrik Michalicka on Unsplash

User defaults are an important way to store small pieces of data in your application.

The implementation of UserDefaults

Remember that UserDefaults is called defaults since they usually refer to the App’s default state at startup or the default behaviour of the Application. Wonderfully UserDefaults is thread safe!

iOS stores NSUserDefaults into a plist file. This means that there is no real benefit to using a plist file over UserDefaults (with some wonderful cache in place), and yet also provides a simple warning.

Never store information in UserDefaults that should be private, and it should be assumed that the file is completely insecure.

The limitations don’t stop there! We can only store key-value pairs and you can write both basic types and even collections or Data values (but be careful when you use object(forKey:) since it returns Any?).

UserDefaults stores it’s magic in the Library/Preferences folder.

Usage: Previously Launched

You can detect whether an app has previously been launched by using UserDefaults which stores a boolean (if nothing is stored it will default…

--

--