tezvyn:

UserDefaults: Your App's Junk Drawer for Settings

AI-drafted, machine-checkedSource: developer.apple.combeginner
UserDefaults: Your App's Junk Drawer for Settings

UserDefaults is a simple key-value store for persisting small bits of data, like a dictionary that saves itself. Use it to remember user preferences like enabling dark mode or a username. The footgun: don't use it for large files or sensitive data.

WHY IT EXISTS: Apps need a simple way to remember user choices and small pieces of state between launches without the complexity of setting up a full database or file-writing system. UserDefaults provides a lightweight, built-in mechanism for this persistence.

THE MENTAL MODEL: Think of UserDefaults as a small dictionary (a key-value map) that your app can write to, and which automatically saves its contents to a file on the device. When the app launches again, it can read from this dictionary to restore its previous state. It's for settings, not for application data.

HOW IT WORKS: You access a shared instance via UserDefaults.standard. You use methods like set(_:forKey:) to save values and typed getters like string(forKey:) or bool(forKey:) to retrieve them. Behind the scenes, iOS saves this data into a property list (.plist) file inside your app's sandboxed container. The entire file is read into memory on access, which is why it's only for small data.

WHEN TO USE IT: Use it for simple, non-critical user preferences. Good examples include: a boolean flag for 'dark mode enabled', a string for the user's name, an integer for a high score, or a date for the last time a feature was used. It's for any small piece of data you want to survive an app restart.

WHEN NOT TO USE IT: Avoid UserDefaults for large data (images, audio, complex JSON responses) as it will slow down your app. It is not a database. Crucially, do not store sensitive information like passwords, API tokens, or personal identifiable information (PII). The data is stored unencrypted and is easily readable on a jailbroken device. Use the Keychain API for secure storage.

ONE CANONICAL EXAMPLE: To save a user's preference for dark mode, you would write: let defaults = UserDefaults.standard followed by defaults.set(true, forKey: "isDarkModeEnabled"). To read it back when the app starts, you would use: let isDarkMode = defaults.bool(forKey: "isDarkModeEnabled"). If the key doesn't exist, bool(forKey:) conveniently returns false.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.