Pocket How
Data and architecture

SwiftData models and queries: @Model, @Query, #Predicate and @ModelActor

iOS 17+, iPadOS 17+. Intermediate. By Cihat Salik, .

Short answer

Mark final classes with @Model, declare relationships with an explicit inverse and delete rule, and read data in views with @Query built in the view's initializer. Keep predicates to stored properties and local constants. Do heavy writes in a @ModelActor and pass PersistentIdentifier values between actors, never model objects.

The problem

SwiftData looks simple in a demo: add @Model, add @Query, done. Real apps then hit the edges. A predicate that compiles crashes at runtime. A relationship without an inverse leaves orphans. A background import blocks scrolling because the “background” actor was created on the main thread. This guide covers the model layer the way you need it in a shipping app, from the first @Model to inheritance on iOS 26.

SwiftData itself needs iOS 17. Where an API is newer, the minimum OS is named next to it.

Define models that age well

A model is a class with the @Model macro (iOS 17). The macro adds PersistentModel and Observable conformance, so SwiftUI views that read a property update when it changes.

import Foundation
import SwiftData

@Model
final class Project {
    var name: String
    var createdAt: Date
    var isArchived: Bool = false

    @Relationship(deleteRule: .cascade, inverse: \Todo.project)
    var tasks: [Todo] = []

    init(name: String, createdAt: Date = .now) {
        self.name = name
        self.createdAt = createdAt
    }
}

@Model
final class Todo {
    var title: String
    var dueDate: Date?
    var priority: Int = 0
    var isDone: Bool = false
    var project: Project?

    init(title: String, dueDate: Date? = nil, project: Project? = nil) {
        self.title = title
        self.dueDate = dueDate
        self.project = project
    }
}

A few habits pay off later:

  • Mark classes final unless you plan to subclass them on iOS 26 (see inheritance below).
  • Give every stored property a default or make it optional when you can. It makes lightweight migrations possible and it is a hard rule if you ever turn on CloudKit sync.
  • Declare the inverse on one side. @Relationship(deleteRule:inverse:) (iOS 17) tells SwiftData which property mirrors which. The default delete rule is .nullify; use .cascade when children make no sense without the parent.
  • Prefer simple stored types. String, numbers, Bool, Date, Data, UUID, URL, Codable structs and enums with raw values all store well. Large blobs belong behind @Attribute(.externalStorage) (iOS 17) so SwiftData can keep them next to the store file.

Two macros from iOS 18 belong in most models. #Index creates single or compound indexes for properties you sort and filter on, and #Unique declares compound unique constraints:

@available(iOS 18, *)
@Model
final class Tag {
    #Unique<Tag>([\.name])
    #Index<Tag>([\.name])

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

Unique constraints turn an insert of an existing value into an upsert. They do not work with CloudKit sync, so decide early which one you want.

Insert, fetch and save with ModelContext

Every read and write goes through a ModelContext. In SwiftUI you get the main one from the environment after attaching a container with .modelContainer(for:) on your scene.

import SwiftUI
import SwiftData

struct NewProjectButton: View {
    @Environment(\.modelContext) private var context

    var body: some View {
        Button("New project") {
            let project = Project(name: "Untitled")
            context.insert(project)
        }
    }
}

The main context autosaves on UI lifecycle events and on a timer after changes, as Apple’s Core Data adoption sample explains. Call try context.save() yourself when you need the write on disk now, for example before handing the store to a widget or an App Intent.

Outside a view, use FetchDescriptor (iOS 17):

func overdueTasks(in context: ModelContext) throws -> [Todo] {
    let now = Date.now
    let never = Date.distantFuture
    var descriptor = FetchDescriptor<Todo>(
        predicate: #Predicate { task in
            !task.isDone && (task.dueDate ?? never) < now
        },
        sortBy: [SortDescriptor(\.dueDate)]
    )
    descriptor.fetchLimit = 50
    return try context.fetch(descriptor)
}

fetchCount(_:) counts without loading objects, fetchIdentifiers(_:) returns only PersistentIdentifier values, and delete(model:where:includeSubclasses:) removes every match in one call. Reach for these before loading thousands of objects just to count or delete them.

Query in views with @Query

@Query (iOS 17) fetches and keeps results live. Static queries go on the property:

struct ActiveProjects: View {
    @Query(filter: #Predicate<Project> { !$0.isArchived },
           sort: \Project.createdAt, order: .reverse)
    private var projects: [Project]

    var body: some View {
        List(projects) { Text($0.name) }
    }
}

When the filter depends on input, such as search text or a selected project, build the query in the initializer. This is the pattern Apple’s own samples use:

struct TaskList: View {
    @Query private var tasks: [Todo]

    init(projectID: PersistentIdentifier, search: String) {
        let predicate = #Predicate<Todo> { task in
            task.project?.persistentModelID == projectID &&
            (search.isEmpty || task.title.localizedStandardContains(search))
        }
        _tasks = Query(filter: predicate,
                       sort: [SortDescriptor(\Todo.priority, order: .reverse),
                              SortDescriptor(\Todo.title)])
    }

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

The parent view changes search, SwiftUI recreates TaskList, and the query reruns. Keep the parent’s state outside the list so the rebuild is cheap.

Know the limits of #Predicate

#Predicate turns a Swift closure into a query the store can run. That conversion is where most surprises live. Paul Hudson’s predicate chapter in SwiftData by Example collects the ones that hurt most, and they match what you will meet:

  • One expression only. No if statements or local let inside the closure. Use &&, || and the ternary operator.
  • Not every String method is supported. hasPrefix and hasSuffix are not; starts(with:) is. lowercased() is not; use localizedStandardContains(_:) for case and diacritic insensitive search.
  • Some code compiles and still crashes. He reports that collection.isEmpty == false crashes while !collection.isEmpty works. Test every predicate against a real store, not just the compiler.
  • Capture values, not expressions. Copy Date.now, a model’s ID or a property of another object into a local constant first, then use the constant inside the predicate.
  • Stored properties only. Computed and @Transient properties have no column, so the store cannot filter on them.

Fatbobman adds a less obvious one: predicates are built from key paths, so every property you filter on has to be visible to the module that builds the predicate. If your models live in a Swift package, those properties need public or package access.

Compare relationships by persistentModelID, as in the TaskList example. Comparing whole model objects inside a predicate is less reliable.

Do heavy work in a @ModelActor

Model objects and ModelContext are not Sendable. You cannot hand a Project from a background task to the main actor. The supported route is a model actor: an actor annotated with @ModelActor (iOS 17), which generates a modelContainer, a modelContext and an initializer, and runs every method on that context’s executor.

import Foundation
import SwiftData

@ModelActor
actor TaskImporter {
    func importTasks(_ titles: [String], into projectID: PersistentIdentifier) throws -> Int {
        guard let project = self[projectID, as: Project.self] else { return 0 }
        for title in titles {
            modelContext.insert(Todo(title: title, project: project))
        }
        try modelContext.save()
        return titles.count
    }

    func archiveFinishedProjects() throws {
        let finished = try modelContext.fetch(
            FetchDescriptor<Project>(predicate: #Predicate { !$0.isArchived })
        ).filter { project in project.tasks.allSatisfy(\.isDone) }
        for project in finished { project.isArchived = true }
        try modelContext.save()
    }
}

Three rules make this work:

  1. Cross actors with PersistentIdentifier. It is Sendable. Pass the ID in, look the object up with the actor’s subscript or modelContext.model(for:), and return IDs or plain value types out. Fatbobman’s Practical SwiftData post builds a whole data layer on this rule, with update and delete methods that take only identifiers.
  2. Save explicitly. A model actor’s context is yours to manage. Save when the unit of work is done.
  3. Create the actor off the main thread. Fatbobman found in Concurrent Programming in SwiftData that a model actor’s context uses the queue of the thread that created it. Created on the main thread, it runs on the main thread, which defeats the purpose.
func runImport(container: ModelContainer, titles: [String], projectID: PersistentIdentifier) {
    Task.detached {
        let importer = TaskImporter(modelContainer: container)
        _ = try await importer.importTasks(titles, into: projectID)
    }
}

ModelContainer is Sendable, so passing it into the detached task is fine. Fatbobman’s other advice is worth following too: create a short-lived actor per operation instead of one global importer. Each one gets a fresh context and nothing stale lingers.

Background saves reach @Query views through the shared store. Developers have reported cases where updates made on a model actor did not refresh views on some iOS 18 releases. If you see that, confirm on the latest OS before building workarounds.

Model inheritance on iOS 26

Since iOS 26, a @Model class can subclass another @Model class. Apple’s inheritance article frames it with trips: a BusinessTrip and a PersonalTrip are both a Trip, share its core properties, and add their own.

@Model
class Trip {
    var name: String
    var startDate: Date
    init(name: String, startDate: Date) {
        self.name = name
        self.startDate = startDate
    }
}

@available(iOS 26, *)
@Model
final class BusinessTrip: Trip {
    var expenseCode: String
    init(name: String, startDate: Date, expenseCode: String) {
        self.expenseCode = expenseCode
        super.init(name: name, startDate: startDate)
    }
}

A query on the base class returns every subclass. Filter by type with is:

@available(iOS 26, *)
func businessOnly() -> Predicate<Trip> {
    #Predicate<Trip> { $0 is BusinessTrip }
}

Apple’s guidance on when to use it is specific. Use inheritance when you query both across the base class and inside a subclass. If you only ever query one specialization, two separate models are simpler. If the difference is a single flag or a small payload, an enum property keeps the model flat. Do not subclass to share one or two common fields; a protocol does that job.

Inheritance changes your schema, so it needs a new VersionedSchema and a migration stage. Early iOS 26 releases also had crash reports on the Apple Developer Forums around relationships typed as the base class. Test on the OS versions you support before you ship it.

What iOS 27 adds

Apple’s SwiftData updates page lists the June 2026 additions. The ones that change everyday model code:

  • ResultsObserver (iOS 27) keeps an observable, optionally sectioned set of results for a fetch outside a view, including changes from other contexts, other processes and CloudKit. It fills the gap that sent UIKit apps back to NSFetchedResultsController.
  • @Attribute(.codable) (iOS 27) stores a property through its Codable representation, including types you do not own.
  • Sectioned queries through a query macro that takes a sectionBy parameter.
  • HistoryObserver (iOS 27) tells you when relevant history transactions arrive from another process or from sync.

Gate them with if #available(iOS 27, *) if you still support iOS 17 through 26.

Checklist

Situation Do this
New model final class, defaults or optionals, inverse on one side, explicit delete rule
Sorting or filtering a large table Add #Index (iOS 18) for those key paths
Natural key like a slug or email #Unique (iOS 18), unless you sync with CloudKit
View with dynamic filter Build Query(filter:sort:) in the view’s init
Predicate crashes at runtime Rewrite as one expression, use supported String methods, capture locals
Import or bulk edit @ModelActor, created in Task.detached, pass PersistentIdentifier
Count or bulk delete fetchCount(_:) or delete(model:where:includeSubclasses:)
Specialized models sharing a base Inheritance on iOS 26, only if you query both base and subclass
Live results outside SwiftUI ResultsObserver on iOS 27

Before you ship, open the store from the previous release with the new build. A model change that looks harmless in code can still need a migration stage.

Sources and further reading

Read next