UserDefaults
In Swift, UserDefaults is a mechanism for persistently storing app settings and small pieces of data. Data is retained even after the app restarts.
Method List
| Method / Property | Description |
|---|---|
| UserDefaults.standard | Provides access to the default database. |
| set(_:forKey:) | Saves a value under the specified key. Supports Bool, Int, Double, String, Data, and more. |
| object(forKey:) | Returns the value for the specified key as Any?. |
| string(forKey:) | Returns the value for the specified key as String?. |
| integer(forKey:) | Returns the value for the specified key as Int. |
| bool(forKey:) | Returns the value for the specified key as Bool. |
| removeObject(forKey:) | Removes the value for the specified key. |
| synchronize() | Forces pending changes to be written to disk (usually not needed). |
Sample Code
import Foundation
let defaults = UserDefaults.standard
// Save values of various types
defaults.set("Alice", forKey: "userName")
defaults.set(25, forKey: "userAge")
defaults.set(true, forKey: "isLoggedIn")
defaults.set(3.14, forKey: "score")
// Read values
let name = defaults.string(forKey: "userName") ?? "Not set"
let age = defaults.integer(forKey: "userAge")
let isLoggedIn = defaults.bool(forKey: "isLoggedIn")
print("Name: \(name)")
print("Age: \(age)")
print("Logged in: \(isLoggedIn)")
// Default value for a missing key
let score = defaults.double(forKey: "score") // Returns 0.0 by default
print("Score: \(score)")
// Save an array or dictionary
let languages = ["Swift", "Kotlin", "Rust"]
defaults.set(languages, forKey: "languages")
if let langs = defaults.array(forKey: "languages") as? [String] {
print("Languages: \(langs)")
}
// Save a Codable type (converted to Data)
struct AppSettings: Codable {
var theme: String
var fontSize: Int
}
let settings = AppSettings(theme: "dark", fontSize: 16)
if let data = try? JSONEncoder().encode(settings) {
defaults.set(data, forKey: "appSettings")
}
if let data = defaults.data(forKey: "appSettings"),
let loaded = try? JSONDecoder().decode(AppSettings.self, from: data) {
print("Theme: \(loaded.theme), Font size: \(loaded.fontSize)")
}
// Remove a value
defaults.removeObject(forKey: "userAge")
print("After removal: \(defaults.object(forKey: "userAge") as Any)")
Overview
UserDefaults is well-suited for persisting small pieces of data such as setting flags, usernames, and the last launch date. Data is stored on disk in the plist format.
To save types not natively supported by UserDefaults (such as custom structs or classes), use Codable to convert them to Data first, then save the Data. UserDefaults is not suitable for storing large amounts of data or sensitive information (such as passwords or authentication tokens). Use Keychain for sensitive data.
For file storage using FileManager, see FileManager.
If you find any errors or copyright issues, please contact us.