How to Handle UserDefaults in Swift
Learn how to easily manage UserDefaults in your iOS application
Introduction
UserDefaults in Swift is a class that provides an interface to save key-value pairs in a user’s stored database.
You can use it to save values that are instances of property lists, like NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.
In this article, I’ll give you a brief introduction on how UserDefaults works and guide you in the creation of a Singleton class, that will manage all the UserDefaults’ related operations in your iOS application.
UserDefaults are mostly used to save app settings or user’s preferences.
Getting and setting values
UserDefaults has two types of methods that will allow you to store values persistently in its database and retrieve that values when needed.
You can use UserDefaults setting methods to set the value for a specified key.
set(_:, forKey: String)
This method takes two parameters:
1. The value you want to save. This can be of any UserDefaults valid type, like Integer, String, Bool, …
2. The key that reference the value.
To retrieve values you can use UserDefaults getting methods:
bool(forKey: String) -> Boolinteger(forKey: String) -> Integerstring(forKey: String) -> String?...
These methods take only one parameter: the key to the value you want to get.
All these methods return a default value if the specified key has not already been set.
In the case of Bool and Integer, these default values are false and 0, respectively.
The String method returns nil as a default, so the return type is an optional String.
You can read a complete list of the UserDefaults methods here.
Class structure
Now, let’s begin with the creation of your UserDefaults class.
Using the singleton pattern will grant easy and global access to the UserDefaults helper class through your code.
The use of this creational pattern guarantees that only one instance of this class is created and gives a universal access point to it.
First, create a new Swift file called Prefs.swift and declare your class in it:
class Prefs {}
Then, make it globally accessible.
class var shared: Prefs {
struct Static {
static let instance = Prefs()
} return Static.instance
}
This subclass contains a static instance of the Prefs class and it will return the same instance every time you reference it in your code.
Now, you can easily use your Prefs class just by calling:
let prefs = Prefs.shared
Handling UserDefaults
Now that we have our main class structure, we can start using it to manage our stored values. In my example, I’ll use the Prefs class to store and retrieve an integer variable.
First, declare a private variable to reference the UserDefaults standard object:
private let defaults = UserDefaults.standard
By calling the standard
property you retrieve the shared defaults object, in which we can read and write the key-value pairs.
To store a value first, you need to declare its key.
A key is a unique string that identifies a value in the UserDefaults.
You can list the keys at the top of the file by declaring:
private let keyIntExample = "intExample"
To reference your values declare a public variable and specify its getter and setter methods.
Every time you reference the variable these methods will be called to retrieve or update the value associated to the key.
var intExample = {
set {
defaults.setValue(newValue, forKey: keyIntExample)
}
get {
return defaults.integer(forKey: keyIntExample)
}
}
Finally, you can easily get or set your integer value just by calling:
// Get the value
let exampleValue = Prefs.shared.intExample// Set the value
Prefs.shared.intExample = 9
Here is the final class structure:
Conclusion
By using this simple class you can now handle UserDefaults in your iOS application avoiding code duplication and syntax errors.
Also, having a single list of your keys in this class will save you from potential key duplication.
Happy coding!