How do you use 'UserDefaults' in Swift?

Instruction: Explain how to save and retrieve data using UserDefaults in Swift.

Context: This question assesses the candidate's knowledge of persisting user preferences or settings within an iOS application using UserDefaults, showcasing their understanding of data persistence on a basic level.

Updated

Official answer

UserDefaults stores small nonsensitive preferences, such as a selected theme or whether a tutorial was shown. It is not a secret store or a database for large datasets. Use Keychain for appropriate secrets; choosing Core Data alone does not make sensitive data secure.

In an app, UserDefaults.standard accesses its usual settings. This complete demonstration uses a unique suite and removes only that suite afterward:

import Foundation

func demonstratePreferences() {
    let suite = "example.preferences." + UUID().uuidString
    guard let defaults = UserDefaults(suiteName: suite) else {
        preconditionFailure("Could not create demonstration suite")
    }
    defer { defaults.removePersistentDomain(forName: suite) }
    defaults.register(defaults: ["theme": "system", "showHints": true])
    assert(defaults.string(forKey: "theme") == "system")
    defaults.set("dark", forKey: "theme")
    assert(defaults.string(forKey: "theme") == "dark")
    defaults.removeObject(forKey: "theme")
    assert(defaults.string(forKey: "theme") == "system")
    assert(defaults.object(forKey: "missingFlag") == nil)
    assert(defaults.bool(forKey: "missingFlag") == false)
}
demonstratePreferences()

Registered defaults are fallback values in a volatile domain; register them at each launch. Removing a stored value can reveal that fallback. Typed accessors differ: string(forKey:) can return nil, while bool(forKey:) returns false for an absent key, so use object(forKey:) when absence itself matters.

Use property-list-compatible values or deliberately encoded Data with a versioned decoding fallback. Read and write through the API, not the underlying files. Changes update the in-memory representation immediately and persist asynchronously; this example checks API behavior, not a crash-durability guarantee. Individual operations are thread-safe, but a read-modify-write sequence is not automatically one atomic transaction.

Keep account-specific preferences separated and clear them according to the product's account policy. Declare required-reason API use in the app's privacy manifest when applicable, using a valid reason matching actual behavior.

UserDefaults types, domains and privacy

Related Questions