Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 46 ยท Data, Networking and Persistence

UserDefaults, @AppStorage and Files

Save small settings with UserDefaults and @AppStorage, and larger data as Codable files in the app sandbox. Learn which folder to use and how to load safely.

Every app has to remember something: the theme the user picked, whether onboarding is finished, the last list they were looking at. If nothing is saved, all of it is gone the next time the app launches. iOS gives you several places to keep data, and the simplest two are UserDefaults for tiny settings and plain files for everything that is too big or too structured for that.

This lesson covers both, plus @AppStorage, the SwiftUI wrapper that connects a view to UserDefaults. You will also learn where the app sandbox lets you write. For anything with queries and relationships, continue to SwiftData. To turn your own types into bytes, you need Codable, and you will reuse it here.

iOS and Xcode cannot run on this site. The UserDefaults and FileManager code below is the real Foundation API running on Linux, so what you see is genuine output. The SwiftUI parts (@AppStorage, view code) are shown in read-only blocks, with a runnable stand-in where it helps.

UserDefaults: a small key-value store

UserDefaults stores values under string keys. It is meant for preferences: a few flags, numbers and short strings. The system saves them for you, in a property-list file inside your app's sandbox, so they survive relaunches.

Reading is forgiving. If a key was never written, bool(forKey:) returns false, integer(forKey:) returns 0, and string(forKey:) returns nil. That is handy, but it can also hide mistakes, so you will see how to set real defaults below.

Swift Writing and reading UserDefaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first three lines show the "zero value" behavior. register(defaults:) does not write anything to disk. It only changes what a read returns when the key is absent, which is why volume is 0.5 even though we never set it. Call it once at launch, before any reads. When you must know whether the user ever chose a value, use object(forKey:), which returns nil for a missing key and a real value (even 0) for a saved one.

What UserDefaults can hold

UserDefaults stores property-list types: Bool, Int, Double, String, URL, Data, Date, and arrays and dictionaries of those. Anything else, such as your own struct, must be converted first. The usual route is Codable to Data.

Swift Saving a Codable struct as Data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice that load() never crashes. The first launch has no data, and the third case holds bytes that are not valid JSON; both fall back to sensible defaults. Treat anything you read from disk as untrusted: an old app version may have written a different shape.

UserDefaults is not a database and not a safe. Do not store large blobs, long lists that grow without limit, or secrets such as passwords and tokens. The data is not encrypted for your app's sake, and it is loaded into memory early at launch. Secrets belong in the Keychain.

@AppStorage: UserDefaults inside SwiftUI

@AppStorage is a property wrapper that reads and writes one UserDefaults key and tells SwiftUI when it changes. You give it the key and a default value. Whenever the value changes, any view that reads it re-renders.

Swift
import SwiftUI

struct SettingsView: View {
    @AppStorage("darkMode") private var darkMode = false
    @AppStorage("fontSize") private var fontSize = 16
    @AppStorage("username") private var username = "Guest"

    var body: some View {
        Form {
            Toggle("Dark mode", isOn: $darkMode)
            Stepper("Font size: \(fontSize)", value: $fontSize, in: 12...32)
            TextField("Name", text: $username)
        }
    }
}

This is a read-only snippet: SwiftUI does not run here. Three things are worth noticing.

  • The value after = is the fallback used when the key is missing. It is not a one-time "initial" value that overwrites saved data.
  • $darkMode is a Binding, so controls can edit the stored value directly.
  • Two different views that use @AppStorage("darkMode") stay in sync. Change it in one place and the other re-renders, because both are watching the same key.

@AppStorage supports Bool, Int, Double, String, URL and Data, plus enums whose raw value is Int or String. For a custom type you can conform it to RawRepresentable with a String raw value, for example by encoding to a JSON string.

A runnable stand-in for the wrapper

You can see the idea behind @AppStorage with a tiny property wrapper of your own. Ours does not notify a view, because there are no views here. It shows only the part that matters for correctness: a key, a fallback and a read-through to UserDefaults.

Swift A mini @AppStorage over UserDefaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Because both Settings values read through to the same UserDefaults, other sees the change made on settings. That is what makes @AppStorage convenient in SwiftUI: the key, not the view, is the source of truth. The real wrapper adds the notification so views refresh.

Pick the right home for data

UserDefaults A few small settings.
Files Documents and cached JSON.
SwiftData Many records you query.
Keychain Passwords and tokens.

If the data grows with use, it is not a preference.

1 / 2

The app sandbox and its folders

Each iOS app runs in a sandbox: a private area of the file system that other apps cannot read. You can create files only inside it. You never hard-code a path, because the location changes between installs. Instead, you ask FileManager for a standard directory.

Swift
let fm = FileManager.default

let documents = try fm.url(for: .documentDirectory, in: .userDomainMask,
                           appropriateFor: nil, create: true)
let support = try fm.url(for: .applicationSupportDirectory, in: .userDomainMask,
                         appropriateFor: nil, create: true)
let caches = fm.urls(for: .cachesDirectory, in: .userDomainMask)[0]
let temporary = fm.temporaryDirectory

Another read-only snippet: the folders are real on a device, so the paths vary. Choose by purpose:

  • Documents is for content the user created or would be sad to lose. It is included in backups.
  • Application Support is for files the app needs that the user does not manage directly: a downloaded database, an offline copy of content. It is also backed up. Create it with create: true, because it may not exist yet.
  • Caches is for data you can rebuild, such as downloaded thumbnails. The system may delete it when storage runs low, so never keep anything irreplaceable there.
  • tmp is scratch space for work in progress. Expect it to be cleaned up.

Saving Codable data to a file

For a moderate amount of structured data, such as a to-do list or a cached feed, encode it to JSON and write it as a file. This is the same pattern you will use in the To-Do project. The standard approach has three rules: write atomically, treat "file missing" as a normal case, and never crash on bad data.

Swift Save and load a Codable file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The .atomic option writes to a temporary file first and swaps it into place, so a crash or power loss in the middle of the write cannot leave you with half a file. load() treats a missing file as an empty list, which is exactly what a first launch looks like. The last line prints the JSON so you can see what ended up on disk: sortedKeys makes the output stable, which also helps tests.

Do slow file work off the main thread for large files, and never block the user interface while reading. For a small JSON file this is fast, but a big import should run in a task. See concurrency in iOS.

Files, versions and migrating

Saved data outlives your app version. When you add a field, old files will not contain it. Make new properties optional or give them defaults with a custom decoder, and keep a version number in the file if you expect real changes. Decoding failures should lead to a clear fallback or a migration step, never a crash. The same thinking applies to UserDefaults keys: if you rename a key, read the old one once, copy it, and remove it.

Which one should I use?

Need Use
A theme, a toggle, a counter @AppStorage or UserDefaults
Per-window state that restores a scene @SceneStorage
A document, an export, a cached feed A file in Documents, Application Support or Caches
Thousands of records you filter and sort SwiftData
A password or token Keychain
Data shared with a widget A UserDefaults suite or file in an App Group container

An App Group is a shared sandbox area that your app and its extensions (such as a widget) can both read. You open it with UserDefaults(suiteName: "group.com.example.myapp"), using the group identifier you enable in the target's capabilities.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A key was never written. What does UserDefaults.standard.integer(forKey: "score") return?

    integer(forKey:) returns 0 for a missing key. Use object(forKey:) to tell a missing key apart from a saved zero.
  2. 2. In @AppStorage("fontSize") var fontSize = 16, what is the 16 for?

    The default only applies while the key is missing. Once the user changes the value, the saved value wins.
  3. 3. Which folder is right for a cache of downloaded thumbnails that you can download again?

    Caches is for data you can rebuild. The system may delete it when storage is low, so do not keep irreplaceable data there.
  4. 4. Why write a file with the .atomic option?

    An atomic write goes to a temporary file first and is then swapped into place, so you get either the old file or the new one, never a broken mix.
  5. 5. Where should a user's password be stored?

    UserDefaults and plain files are not meant for secrets. The Keychain is the system store designed for passwords and tokens.

Summary

  • UserDefaults stores small preferences as property-list types under string keys; use register(defaults:) for fallbacks and object(forKey:) to detect a missing key.
  • @AppStorage binds a view to one UserDefaults key and re-renders when it changes; the value after = is only a fallback.
  • Custom types are stored by encoding them with Codable to Data, and decoding must fail safely.
  • The app sandbox gives you Documents, Application Support, Caches and tmp; choose by how important and how rebuildable the data is.
  • Write files with .atomic, treat a missing file as normal, and plan for old data shapes.
  • Large or queryable data belongs in SwiftData, and secrets belong in the Keychain.

Next: SwiftData Basics