If you'd like to store simple data permanently on a device to ensure it's available when your app restarts, the best option is to use UserDefaults.
It's important to understand that UserDefaults is not a database and should only be used for saving simple data, such as user preferences (e.g., background color, menu state, etc.).
The types of variables that can be stored include:
- String
- Int
- Float
- Double
- Bool
- Data
- Arrays of the above types
- Dictionaries with the above types
Saving Data
Save data in UserDefaults using the function set()
. It requires a unique id as parameter which will be used to load the data we saved.
import Foundation
let username = "Pablo"
UserDefaults.standard.set(username, forKey: "USERNAME_KEY")
Loading Data
To load data we need to use an specific function for that data type. In this case we want to load a String
.
import Foundation
let username = UserDefaults.standard.string(forKey: "USERNAME_KEY")
These functions return an Optional
value that will be nil in case no value is found for the specified id.
Deleting Data
import Foundation
UserDefaults.standard.removeObject(forKey: "USERNAME_KEY")
UserDefaults containers
UserDefaults.standard
is the default container where our data will be stored. However you can use multiple containers in the same App just using specifying a container identifier.
import Foundation
let settingsDefaults = UserDefaults(suiteName: "Settings")
settingsDefaults?.set(false, forKey: "DARK_BACKGROUND")
let profileDefaults = UserDefaults(suiteName: "Profile")
profileDefaults?.set(true, forKey: "AUTO_LOGIN")
Be the first to comment