Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 46 ยท Data, Networking and Persistence

SwiftData Basics

Store app data with SwiftData: define models with @Model, set up a ModelContainer, fetch with @Query, insert and delete, add relationships and filter with predicates.

When an app has hundreds of records that you search, sort and edit, a JSON file or UserDefaults stops being comfortable. You need a real database: something that loads only what you ask for, keeps relationships between records and saves changes safely. On Apple platforms, the modern answer for SwiftUI apps is SwiftData. You describe your data as ordinary Swift classes, and the framework stores them, tracks changes and updates your views.

This lesson explains the four ideas you need: the @Model macro, the ModelContainer, the ModelContext and the @Query property wrapper. It assumes you know @Observable models and the Environment. SwiftData needs iOS 17 or later, and it cannot run on this site. The SwiftUI and SwiftData code is read-only. The runnable examples are small stand-ins written in plain Swift. They show how fetching, predicates and relationships behave, and they use the real #Predicate and SortDescriptor types from Foundation.

Models are classes with @Model

A SwiftData model is a class marked with the @Model macro. Every stored property becomes persistent, and the macro also makes the class observable, so a SwiftUI view re-renders when a property changes.

Swift
import SwiftData

@Model
final class Note {
    var title: String
    var body: String
    var isPinned: Bool
    var createdAt: Date

    init(title: String, body: String = "", isPinned: Bool = false, createdAt: Date = .now) {
        self.title = title
        self.body = body
        self.isPinned = isPinned
        self.createdAt = createdAt
    }
}

Properties can be basic types (String, Int, Double, Bool, Date, URL, UUID, Data), optionals, arrays, Codable structs and enums, and other models. A few attributes tune the storage:

  • @Attribute(.unique) asks the store to keep one record per value, for example one account per email address.
  • @Transient marks a property that is not saved, such as a cached calculation.
  • @Attribute(originalName: "title") tells the store that a property was renamed, which helps migrations.

You do not write an id property. Every model has a persistent identifier, and models conform to Identifiable, so ForEach and List work with them directly.

The container and the context

Two objects do the work behind the scenes.

  • A ModelContainer owns the storage: which model types exist, and where the data lives (a file on disk, or memory only for previews and tests).
  • A ModelContext is the scratch pad you work in. You insert, change and delete models in a context, and it saves them to the container's store.

In SwiftUI, one modifier creates the container and puts its main context into the environment for the whole view tree:

Swift
import SwiftUI
import SwiftData

@main
struct NotesApp: App {
    var body: some Scene {
        WindowGroup {
            NotesListView()
        }
        .modelContainer(for: Note.self)
    }
}

For previews and tests you usually want a container that never touches the disk:

Swift
let configuration = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(for: Note.self, configurations: configuration)

By default, the context from modelContainer(for:) saves automatically at sensible moments, such as when the app goes to the background. You can also call try context.save() yourself when you want to be sure a change reached the store.

Four pieces of SwiftData

@Model A class whose properties are stored.
ModelContainer Owns the store and the schema.
ModelContext Where you insert, edit and delete.
@Query Fetches models into a view.

The container is created once; contexts do the daily work.

1 / 2

Reading data with @Query

@Query runs a fetch for you and keeps the result up to date. When a matching model is inserted, changed or deleted, the view re-renders. You never write a loading function or refresh code.

Swift
struct NotesListView: View {
    @Environment(\.modelContext) private var context
    @Query(sort: \Note.createdAt, order: .reverse) private var notes: [Note]

    var body: some View {
        NavigationStack {
            List {
                ForEach(notes) { note in
                    Text(note.title)
                }
                .onDelete { offsets in
                    for index in offsets {
                        context.delete(notes[index])
                    }
                }
            }
            .navigationTitle("Notes")
            .toolbar {
                Button("Add") {
                    context.insert(Note(title: "New note"))
                }
            }
        }
    }
}

This is real SwiftData code, shown read-only. Look at how little there is. The view does not store the notes in @State. @Query is the source of truth. To add a note you insert into the context, and the list updates by itself. To delete, you call context.delete. This is the same "view is a function of data" idea from the SwiftUI mental model, with the database as the data.

Editing

Because models are observable, you edit them in place. To connect a text field to a model property, use @Bindable:

Swift
struct NoteEditor: View {
    @Bindable var note: Note

    var body: some View {
        Form {
            TextField("Title", text: $note.title)
            TextEditor(text: $note.body)
            Toggle("Pinned", isOn: $note.isPinned)
        }
    }
}

There is no save button. The change is made on the model in the main context and saved automatically.

Filtering and sorting with predicates

@Query accepts a filter written with the #Predicate macro. It looks like an ordinary Swift closure, but the compiler turns it into a structured description that can be translated for the store. That means it supports a subset of Swift: comparisons, &&, ||, !, and some string and collection methods. Arbitrary function calls are not allowed.

Swift
@Query(
    filter: #Predicate<Note> { $0.isPinned && $0.title.contains("Swift") },
    sort: [SortDescriptor(\Note.createdAt, order: .reverse)]
)
private var pinnedSwiftNotes: [Note]

A @Query is configured when the view is created, so a search box needs one more trick: build the query in the view's init.

Swift
struct SearchableNotes: View {
    @Query private var notes: [Note]

    init(searchText: String) {
        let filter = #Predicate<Note> { note in
            searchText.isEmpty || note.title.localizedStandardContains(searchText)
        }
        _notes = Query(filter: filter, sort: \.createdAt, order: .reverse)
    }

    var body: some View {
        List(notes) { Text($0.title) }
    }
}

The parent holds the search text in @State and creates SearchableNotes(searchText: text). Each new text produces a view with a new query.

A stand-in you can run

The real #Predicate and SortDescriptor types come from Foundation, so we can use them here. The stand-in below has a tiny MiniContext with insert, delete, save and fetch. It reproduces one important behavior: inserted objects are not visible to a fetch until they are saved, in this simplified model. (A real ModelContext is smarter than this and also sees its own unsaved changes. The stand-in simply makes the save step visible.)

Swift A mini context with real predicates

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 two #Predicate closures are exactly the syntax you would pass to a real @Query. In SwiftData the store runs the filter in the database, while here we evaluate it in memory. Either way, you describe what you want, and sorting is a separate list of SortDescriptor values.

Relationships

Models can point to other models. A folder has many notes, and each note belongs to one folder. You declare the link as a normal property, and @Relationship lets you choose the delete rule and the inverse.

Swift
@Model
final class Folder {
    var name: String
    @Relationship(deleteRule: .cascade, inverse: \Note.folder)
    var notes: [Note] = []

    init(name: String) { self.name = name }
}

@Model
final class Note {
    var title: String
    var folder: Folder?

    init(title: String, folder: Folder? = nil) {
        self.title = title
        self.folder = folder
    }
}

The inverse means both sides stay in step: when you set note.folder, the folder's notes array contains the note, and the other way around. The delete rule says what happens to the notes when their folder is deleted:

  • .cascade deletes the notes too.
  • .nullify (the default) keeps the notes and sets their folder to nil.
  • .deny refuses to delete a folder that still has notes.
  • .noAction does nothing and leaves your data to you, which is rarely what you want.

Relationship properties that point to a single model should be optional, because the other side may be gone. The stand-in below plays out the cascade and nullify rules.

Swift Delete rules in a stand-in

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.

Choose the rule by asking "Does a child make sense without its parent?" Notes without a folder are fine, so .nullify fits. Line items without their order are meaningless, so .cascade fits.

Migrations: changing the model later

Your model will change after release: a new property, a rename, a split. SwiftData stores a schema with the data, and when the schema changes it must migrate the existing data. Simple changes are handled automatically (this is called a lightweight migration): adding a property that is optional or has a default value, or removing a property. For anything else, you describe the versions yourself.

Swift
enum SchemaV1: VersionedSchema {
    static var versionIdentifier = Schema.Version(1, 0, 0)
    static var models: [any PersistentModel.Type] { [Note.self] }
    // The Note class as it shipped in version 1 lives inside this enum.
}

enum NotesMigrationPlan: SchemaMigrationPlan {
    static var schemas: [any VersionedSchema.Type] { [SchemaV1.self, SchemaV2.self] }
    static var stages: [MigrationStage] {
        [MigrationStage.lightweight(fromVersion: SchemaV1.self, toVersion: SchemaV2.self)]
    }
}

This is an outline, not a complete project: each schema version contains its own copy of the model classes. Use a custom stage when you need code to transform data, for example to split one name field into firstName and lastName. Plan for migrations from the first release, and test them with a copy of old data. A crash at launch because the store cannot be opened is one of the worst bugs an app can have.

Practical tips

  • Give properties defaults or make them optional. New properties then migrate cleanly.
  • Keep models for storage. If a screen needs derived values or formatting, put that in a view model or computed property. See MVVM in SwiftUI.
  • Do not hold models across threads. A context belongs to one actor. Background work should use its own context.
  • Use in-memory containers for previews and tests, with sample data inserted in code.
  • Syncing across devices is possible with iCloud, but it adds rules: no unique constraints, and every property needs a default or must be optional. See Core Data, CloudKit and Sync.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the @Model macro do to a class?

    @Model makes stored properties persistent and lets SwiftUI observe changes. It does not turn the class into a view, and iCloud sync is a separate opt-in.
  2. 2. Which type is the scratch pad where you call insert and delete?

    The container owns the storage, while the ModelContext is where you insert, change and delete models. @Query reads data into a view.
  3. 3. A folder is deleted with the .nullify delete rule. What happens to its notes?

    .nullify keeps the children and clears the link. .cascade would delete them, and .deny would refuse the delete.
  4. 4. Why does a searchable list build its @Query inside the view's init?

    A @Query is fixed when the view is created. Passing the search text to init and assigning _notes = Query(...) makes each new text produce a new query.
  5. 5. Which change can usually be migrated automatically (a lightweight migration)?

    Adding an optional or defaulted property is a lightweight change. Splitting, merging and re-typing data need a custom migration stage.

Summary

  • A SwiftData model is a class marked @Model; its stored properties are persisted and observed.
  • A ModelContainer owns the storage (disk or memory), and the ModelContext is where you insert, edit, delete and save.
  • .modelContainer(for:) on a scene creates the container and puts the main context in the environment.
  • @Query fetches and keeps results fresh; use filter: with #Predicate and sort: with key paths or SortDescriptor.
  • Dynamic filters are built in the view's init with _property = Query(...).
  • @Relationship sets inverses and delete rules (cascade, nullify, deny); relationship properties to one model are optional.
  • Plan migrations early: defaulted or optional new properties are lightweight, bigger changes need a versioned schema and a migration plan.

Next: Core Data, CloudKit and Sync