Back to course overview
Module 4Data & persistence 12 min

Storing data with SwiftData

Understand what SwiftData actually does for you, and the three operations — insert, query, delete — that cover most apps.

You already used SwiftData in Module 3 without dwelling on it. Now let's make it explicit, because persistence is where beginners get mysterious bugs. SwiftData is Apple's framework for saving Swift objects to disk and keeping your UI in sync with them — no database code, no SQL.

The three moving parts

  • `@Model` — the annotation on your class (Entry) that makes instances savable.
  • The model container — the on-disk store, registered once with .modelContainer(for: Entry.self) at the app's root.
  • The model context — the in-memory workspace you insert, edit, and delete through. You reach it with @Environment(\.modelContext).

The operations you'll actually use

swiftswift
// CREATE — insert a new object
context.insert(Entry(body: "First entry"))

// READ — a live, auto-updating query in a view
@Query(sort: \Entry.createdAt, order: .reverse) var entries: [Entry]

// UPDATE — just mutate the object; SwiftData tracks the change
entry.body = "Edited text"

// DELETE — remove it from the context
context.delete(entry)
You usually don't call save()

SwiftData autosaves changes for you at sensible moments. You can call context.save() explicitly (and should before critical transitions), but forgetting it is rarely the cause of a bug. Inserting into the wrong context, or not inserting at all, usually is.

The #1 SwiftData gotcha

If you create an object but never context.insert it (or never attach it to another inserted object), it silently won't persist. When 'my data disappears on relaunch,' check that every object reaches the context.

Prompt to try

In my SwiftData iOS 17+ app, entries created in EntryEditorView aren't showing after relaunch. Here's the editor file and my app entry point: [paste both]. Diagnose why data isn't persisting and give me the corrected code.

A great example of using AI to debug a persistence issue — give it both the writer and the container setup.