UserDefaults is a simple and efficient way to store small pieces of data persistently on the device. This can be useful for saving user preferences, settings, or any other data that needs to be accessed across app launches. In this tutorial, we will explore how to work with UserDefaults in Swift.
To save data to UserDefaults, you can use the set method with a specific key:
// Saving data to UserDefaults
UserDefaults.standard.set("John Doe", forKey: "username")}
To retrieve the data stored in UserDefaults, you can use the object(forKey:) method:
// Retrieving data from UserDefaults
if let username = UserDefaults.standard.object(forKey: "username") as? String {
print("Username: \(username)")
}
You can check if a value exists for a particular key in UserDefaults using the objectForKey method. If the value is nil, it means that no data is stored for that key:
if UserDefaults.standard.object(forKey: "username") == nil {
print("No username saved in UserDefaults")
}
To remove data from UserDefaults, you can use the removeObject(forKey:) method:
// Removing data from UserDefaults
UserDefaults.standard.removeObject(forKey: "username")}
You can also store complex data types such as arrays, dictionaries, and custom objects in UserDefaults by using the set method with the appropriate type:
// Saving an array to UserDefaults
let favorites = ["Apple", "Banana", "Orange"]
UserDefaults.standard.set(favorites, forKey: "favorites")
// Retrieving the array from UserDefaults
if let savedFavorites = UserDefaults.standard.array(forKey: "favorites") as? [String] {
print("Favorites: \(savedFavorites)")
}
Remember that UserDefaults should not be used to store sensitive information such as passwords or tokens. It is best suited for small, non-sensitive data that needs to persist between app launches.