Contact
← Back to Topics

User Defaults

Simple key-value store for persisting small amounts of data between app launches.

About User Defaults

UserDefaults is a lightweight persistence mechanism provided by iOS for storing small amounts of data as key-value pairs. It's ideal for storing user preferences, settings, and other small pieces of data that need to persist between app launches.

Key Features

  • Simple key-value storage
  • Automatic synchronization
  • Primitive data type support
  • Property list compatibility
  • Notification on changes

Code Example

// UserDefaults example
import UIKit

// Saving data
UserDefaults.standard.set("John Appleseed", forKey: "username")
UserDefaults.standard.set(42, forKey: "highScore")
UserDefaults.standard.set(true, forKey: "isFirstLaunch")
UserDefaults.standard.set(Date(), forKey: "lastLoginDate")

// Arrays and dictionaries
let favorites = ["Swift", "UIKit", "CoreData"]
UserDefaults.standard.set(favorites, forKey: "favoriteTopics")

let settings = ["darkMode": true, "notificationsEnabled": true]
UserDefaults.standard.set(settings, forKey: "userSettings")

// Reading data
let username = UserDefaults.standard.string(forKey: "username") ?? "Guest"
let highScore = UserDefaults.standard.integer(forKey: "highScore")
let isFirstLaunch = UserDefaults.standard.bool(forKey: "isFirstLaunch")
let lastLogin = UserDefaults.standard.object(forKey: "lastLoginDate") as? Date

// Reading arrays and dictionaries
let storedFavorites = UserDefaults.standard.array(forKey: "favoriteTopics") as? [String] ?? []
let storedSettings = UserDefaults.standard.dictionary(forKey: "userSettings") as? [String: Any] ?? [:]