A Guide to Using UserDefaults in Swift
UserDefaults is a powerful and convenient way to store small amounts of data in your iOS or macOS applications. It provides a simple interface to persistently store and retrieve data such as user preferences, settings, and application state. In this article, we will explore how to use UserDefaults in Swift with practical code examples.
Setting Up UserDefaults
To get started, you need to import the Foundation framework and get a reference to the shared UserDefaults instance, which is available throughout your application.
import Foundation
// Get a reference to UserDefaults
let defaults = UserDefaults.standard
Storing and Retrieving Values
UserDefaults provides various methods to store and retrieve different types of values. Let’s look at some common scenarios.
Storing and retrieving String values
// Storing a String
defaults.set("John Doe", forKey: "username")
// Retrieving a String
if let username = defaults.string(forKey: "username") {
print("Username: \(username)")
}
Storing and retrieving Integer values
// Storing an Integer
defaults.set(25, forKey: "age")
// Retrieving an Integer
let age = defaults.integer(forKey: "age")
print("Age: \(age)")
Storing and retrieving Boolean values
// Storing a Boolean
defaults.set(true, forKey: "isPremiumUser")
// Retrieving a Boolean
let isPremiumUser = defaults.bool(forKey: "isPremiumUser")
print("Is Premium User: \(isPremiumUser)")
Storing and retrieving Custom Objects (with Codable)
UserDefaults also supports storing and retrieving custom objects that conform to the Codable protocol. Here’s an example:
// Define a custom object
struct Person: Codable {
let name: String
let age: Int
}
// Storing a custom object
let person = Person(name: "Alice", age: 30)
let encoder = JSONEncoder()
if let encodedData = try? encoder.encode(person) {
defaults.set(encodedData, forKey: "person")
}
// Retrieving a custom object
if let storedData = defaults.data(forKey: "person") {
let decoder = JSONDecoder()
if let decodedPerson = try? decoder.decode(Person.self, from: storedData) {
print("Person: \(decodedPerson.name), Age: \(decodedPerson.age)")
}
}
Removing Values
If you want to remove a stored value from UserDefaults, you can use the removeObject(forKey:)
method:
defaults.removeObject(forKey: "username")
Synchronizing Changes
By default, UserDefaults automatically saves changes to disk periodically. However, you can manually trigger a save operation using the synchronize()
method:
defaults.synchronize()
Conclusion
UserDefaults provides a simple and efficient way to store and retrieve user preferences and small amounts of data in your Swift applications. In this article, we explored how to use UserDefaults to store and retrieve different types of values, including strings, integers, booleans, and even custom objects. Understanding how to leverage UserDefaults will help you build more robust and user-friendly applications.
👏🏽 Give this story a CLAP
👉🏽 Subscribe for upcoming articles
💰 Access Free Mobile Development tutorials
🔔 Follow for more
See you on next article 👋