Swift UserDefaults
is a lightweight and convenient data persistence store provided by Apple’s Foundation framework. It allows you to store small pieces of data, such as user preferences, settings, and simple configuration values. These values are automatically saved to the device’s file system, making them accessible even after the app is closed or the device is rebooted.
What can be stored in UserDefaults?
You can store pretty much anything in UserDefaults
but it’s not where you want to store large amounts of data. UserDefaults is great if you want to store something simple like a bool.
Let’s say you have a intro flow you only wants to show once, in this case when the user a seen the introflow, you simply set a UserDefaults
to true and every time the app comes to foreground you check that value.
You have to keep in mind that the data you store in UserDefaults
is not secure, so if you are looking for a secure data storage then take a look at keychain
— so for example, if you want to store a access token to an API, you should use KeyChain
but if you want to store the logged in username you can use UserDefaults
.
How to use UserDefaults in Swift
You can store many different types of data in UserDefaults
and therefore making it a great tool. In the following examples we will go through how to save and retrieve the different data types.
When saving UserDefaults
the syntax is the same for every type and for reading from UserDefaults
you just need to specify what type of data you are fetching.
When you are creating or fetching from UserDefaults
you need to specify what key the data has, and that is done with a simple string and by using the parameter forKey
.
Swift UserDefaults with integer
How to save a integer in UserDefaults
:
UserDefaults.standard.set(10, forKey: "integer-storage")
How to get a integer from UserDefaults
:
UserDefaults.standard.integer(forKey: "integer-storage")
//That will fetch the integer 10 in our example
And if the key doesn’t exist the default value is: 0
Swift UserDefaults with string
How to save a string in UserDefaults
:
UserDefaults.standard.set("Hello UserDefaults", forKey: "string-storage")
How to get a string from UserDefaults
:
UserDefaults.standard.string(forKey: "string-storage")
//That will fetch the optional string: Optional("Hello UserDefaults")
And if the key doesn’t exist the default value is: nil
and if the values exists it will be a Optional string.
Swift UserDefaults with bool
How to save a bool
in UserDefaults
:
UserDefaults.standard.set(true, forKey: "bool-storage")
How to get a bool
value from UserDefaults
:
UserDefaults.standard.bool(forKey: "bool-storage")
//That will fetch the bool true
And if the key doesn’t exist the default value is: false
Swift UserDefaults with double
How to save a double in UserDefaults
:
UserDefaults.standard.set(2.5, forKey: "double-storage")
How to get a double from UserDefaults
:
UserDefaults.standard.double(forKey: "double-storage")
//That will fetch the double 2.5
And if the key doesn’t exist the default value is: 0.0
Swift UserDefaults with array
How to save a array in UserDefaults
:
UserDefaults.standard.set(["One","Two","Three"], forKey: "array-storage")
How to get a array from UserDefaults
:
UserDefaults.standard.array(forKey: "array-storage")
//That will fetch the optional array Optional([One, Two, Three])
And if the key doesn’t exist the default value is: nil
Swift UserDefaults with date
How to save a date in UserDefaults
:
UserDefaults.standard.set(Date.now, forKey: "date-storage")
How to get a date from UserDefaults
:
UserDefaults.standard.object(forKey: "date-storage")
//That will fetch the optional date: Optional(2023-08-11 05:54:41 +0000)
And if the key doesn’t exist the default value is: nil
How do I save an object in UserDefaults?
This is properly the one people struggle with the most, so let’s dive into in — and don’t worry, it’s not that difficult.
First we create our custom object/class, we will name it User. Next we need to use JSONEncoder
to encode that object to data.
User object:
struct User {
let name: String
let age: Int
}
How to save custom object in UserDefaults
:
let userToSave = User(name: "John", age: 42)
do {
let encoder = JSONEncoder()
let data = try encoder.encode(userToSave)
UserDefaults.standard.set(data, forKey: "user")
} catch {
print(error)
}
How to get a custom object from UserDefaults
:
if let data = UserDefaults.standard.data(forKey: "user") {
do {
let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: data)
} catch {
print("Unable to Decode Note (\(error))")
}
}
How to remove one UserDefaults
We can save and get different values from UserDefaults
, now it’s time to remove them aswell.
We can remove one UserDefault, no matter that type it is like this:
UserDefaults.standard.removeObject(forKey: "key-to-remove")
Swift UserDefaults remove all
Sometimes you want to remove all of the objects from UserDefaults
and just reset it completely.
Where is a few ways of doing this, you can loop every UserDefaults
key and use .removeObject.
But that can be a lot of work – luckily Apple have thought of that and made it easy for us.
We can simply use the following line and it will remove all UserDefaults
:
if let bundle = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName:bundle)
}
Optimise your work with UserDefaults
You have learned the basics of working with UserDefaults
in Swift, now it’s time to optimize it for a real life app.
The big issue with UserDefaults
is that the key is a simple string and therefore it’s easy to make a spelling error — we need to remove the potential issue.
We will do this in two steps: Make UserDefaultsKeys
struct and make a helper class.
Make UserDefaultsKeys helper
The first thing we will do is make a struct where you write your keys, so you only have to write your keys one time:
struct UserDefaultKeys {
static let userKey = "user"
}
Now you can use your keys like this:
UserDefaultKeys.userKey
By doing this we only write our UserDefaults
keys one place and can easily re-use them throughout our app without any spelling mistakes.
Make a UserDefaults helper class
To take it a step further we can also make a UserDefaults
helper class where we do all out UserDefaults
work and just call that helper class throughout our app:
final class UserDefaultHelper {
static let standard = UserDefaultHelper()
func setUserName(userName: String) {
UserDefaults.standard.set(userName, forKey: UserDefaultKets.userKey)
}
}
In our app we can now just call that function like this:
UserDefaultHelper.standard.setUserName(userName: "John")
With this helper class it makes it’s it easy for us and other to know what that key is for.
Wrap up on UserDefaults
Swift UserDefaults
offers a straightforward and effective way to manage small-scale data persistence in iOS apps.
While UserDefaults
is not suited for storing large amounts of data or sensitive information, its simplicity and ease of use make it an invaluable tool in your iOS applications.