skip to content

SwiftData

SwiftData is the Swift-native persistence layer built on Core Data, declaring models with macros instead of a model editor. Interviewers compare it with Core Data and ask where it still falls short.

on this pageshow

explore

questions

30

In SwiftData, what is the difference between a ModelContainer and a ModelContext, and which one do you insert and delete models through?

level: juniorimportance: must knowfreq 75%

answer

  1. two objects, two jobs
  2. schema and store vs workspace
  3. insert and delete live on one
  4. changes wait for a save
  5. container's mainContext is main-actor bound

basics

~20 s

A ModelContainer owns the schema and the persistent store; a ModelContext is the in-memory workspace where you insert, delete, edit and save models. You call insert(:) and delete(:) on a context, often the container's mainContext.

solid answer

~40 s

`ModelContainer` is the long-lived object that knows your app's schema and manages the store behind it: it does the actual reads and writes when a fetch runs or a context saves. `ModelContext` is where model objects live while you work with them: you call `insert(_:)` to register a new model, `delete(_:)` to mark one for removal, and simply set properties to edit one, because the context tracks changes on models it knows. Nothing reaches the store until the context saves, either through `save()` or autosave. Every container exposes `mainContext`, a context bound to the main actor, and you can create more with `ModelContext(container)`. An app has at least one container and usually several contexts.

code

swift · 23 lines
swift
import SwiftData
import Foundation

@Model final class Inspection {
    var siteName: String
    var inspectedAt: Date
    init(siteName: String, inspectedAt: Date) {
        self.siteName = siteName
        self.inspectedAt = inspectedAt
    }
}

@MainActor
func recordVisit(in container: ModelContainer) throws {
    let context = container.mainContext
    let visit = Inspection(siteName: "Pump station 4", inspectedAt: .now)
    context.insert(visit)        // tracked, not yet on disk
    visit.siteName = "Pump station 4B"   // no update call needed
    try context.save()           // writes the insert and the edit

    context.delete(visit)        // removed at the next save
    try context.save()
}

go deeper

for a junior

Recall the split: the container owns schema and store, the context is where you insert, edit, delete and save. Know that mainContext is the container's main-actor context.

for a middle

Explain that edits are tracked automatically, that delete and insert are pending until a save, and that inserting a graph's root inserts its related models.

for a senior

Show you know where each context may be used: mainContext belongs to the main actor, other work needs its own context on the same container, and unsaved changes live only in that context.

for a principal

Frame the container as the app's single persistence boundary and contexts as units of work, and say how a team keeps that boundary consistent across features and tests.

## Two objects, two jobs SwiftData splits persistence into two objects, and many beginner bugs come from mixing up which one does what. | | `ModelContainer` | `ModelContext` | |---|---|---| | What it holds | The **schema** (your `@Model` types) and one or more store configurations | The model objects you are working with right now | | Lifetime | Usually one for the app's whole run | Many; short or long-lived | | What you call on it | Creation, `mainContext`, `configurations` | `insert(_:)`, `delete(_:)`, `fetch(_:)`, `save()`, `rollback()` | | Touches the store? | Yes: it performs reads and writes | Only through its container, when it fetches or saves | Apple's documentation describes the **container** as the object that "mediates between its associated model contexts and your app's underlying persistent storage": whenever a fetch runs or a context calls `save()`, the container performs the actual read or write. The **context** is the object that "enables you to fetch, insert, and delete models, and save any changes to disk". ## Creating them - `ModelContainer(for: Inspection.self)` builds a container for one model type; it **throws**, because opening or migrating a store can fail. - Passing no `ModelConfiguration` is allowed: SwiftData builds a default configuration from your app's entitlements and the type's default values. - Every container has a `mainContext` property, declared `@MainActor`, so you read it from main-actor code such as a view or a main-actor view model. - `ModelContext(container)` creates an additional context on the same container, for example for work that should not run on the main actor. ## Inserting, editing and deleting The context is the only place you change data: 1. **Insert**: create the model with its normal initializer, then call `context.insert(model)`. Until then the object is just a Swift instance the store knows nothing about. 2. **Edit**: set its properties. There is no update method, because the context tracks every change to models it has inserted or fetched. 3. **Delete**: call `context.delete(model)`. The documentation says SwiftData removes the model from the store **during the next save**; if the model was new and never saved, the context simply discards it. To delete many at once, `delete(model:where:includeSubclasses:)` takes a type and an optional predicate, and with no predicate it removes every model of that type. When models are related, you insert only the root of a new graph: the context recognises the relationships and inserts the related models with it, even when the graph mixes new and existing models. ## Nothing is on disk until a save Inserts, edits and deletes are **pending** in the context's memory. They reach the store when the context saves, either because you call `save()` or because the context's `autosaveEnabled` is on and it saves by itself. SwiftData switches autosave on for the container's `mainContext`; the context properties `hasChanges`, `insertedModelsArray`, `changedModelsArray` and `deletedModelsArray` show what is still pending. Exactly when autosave fires, and why a background context needs explicit saves, are their own topics; the point here is that the context, not the container, holds unsaved work. ## Where each object lives in an app - **One container, created early.** Most apps build a single `ModelContainer` at launch and share it; everything that reads or writes the same store goes through it. - **The main context for the UI.** Views and main-actor view models use `mainContext`, which is why it is the context SwiftUI code normally sees. - **More contexts for separate units of work.** An import, an export or a test creates its own context with `ModelContext(container)`, so its pending changes stay apart from the UI's until it saves. - **A fresh container per test.** Tests build their own, usually in memory, so no test sees another's rows. ## Mistakes interviewers listen for - Treating the container as the thing you insert into. `ModelContainer` has no `insert(_:)`; you always go through a context. - Expecting a newly created model object to be persistent because it was initialised. It is not tracked until a context inserts it. - Assuming `delete(_:)` removes the row immediately. It marks the model; the save writes the removal. - Inserting each child of a new object graph one by one. Inserting the root is enough. - Reaching for `mainContext` from a background task. It is declared `@MainActor`; work off the main actor uses a context of its own. Installing the container in a SwiftUI scene and reading the context from the environment are covered with SwiftData's SwiftUI integration; reading data with fetch descriptors and predicates is covered with querying and fetching.

  • If a new Inspection owns several new Photo models through a relationship, do you insert each one?
    No. Insert the root of the graph and the context recognises the relationships and inserts the related models too. Apple's documentation says this holds even when the graph mixes new and existing models, so one `insert(_:)` on the inspection is enough.
  • What happens if you call delete(_:) on a model you inserted but never saved?
    The context discards it. `delete(_:)` normally removes the model from the store at the next save, but a new, unsaved model has nothing in the store, so the context just drops the pending insert and nothing is ever written.
  • How many containers and contexts does a typical app have?
    At least one container, often exactly one for the app's store, shared by everything. Contexts are cheap and plentiful: the container's `mainContext` serves main-actor code such as views, and work off the main actor creates its own context on the same container.

The container is the archive building with its filing rules; a context is a clerk's desk. You draft, correct and strike out papers on the desk, and nothing changes in the archive until the clerk files the batch.

  • You insert models into the ModelContainer directly.
  • A model is saved as soon as you create it with its initializer.
  • You must call an update method on the context after changing a property.
  • delete(_:) removes the row from the store immediately.
  • Every model in a new related graph needs its own insert(_:) call.
  • The container's mainContext can be used from any thread.
open as a page

In SwiftData, what does marking a class with the @Model macro give you, and why must a model be a class rather than a struct?

level: juniorimportance: must knowfreq 75%

basics

~20 s

@Model makes a class persistable: it adds PersistentModel and Observable conformance and rewrites each stored property to read and write SwiftData's backing data. It must be a class because PersistentModel is class-only and a context tracks each instance by identity.

open as a page

With SwiftData's @Query, how do you show a library's books in a SwiftUI List sorted by title, and when does that list update?

level: juniorimportance: must knowfreq 75%

basics

~20 s

Declare @Query(sort: \Book.title) var books: [Book] in the view and hand books to List. The query fetches from the environment's model context and stays in sync, so inserts, deletes and edits redraw the list without a refetch.

open as a page

In SwiftData, how do you declare that a Project model owns many Task models, with each task pointing back to its project?

level: juniorimportance: must knowfreq 65%

basics

~20 s

Give Project an array property of the task model and give the task an optional Project property. Name the pairing with @Relationship(inverse:) on one of the two, and SwiftData keeps both ends of the link in sync.

open as a page

In a SwiftUI app using SwiftData, how do you install the model container with the modelContainer modifier and reach the model context from a view?

level: juniorimportance: must knowfreq 72%

basics

~10 s

Apply modelContainer(for: Entry.self) to the WindowGroup or the root view. SwiftData builds the container and puts its main-actor ModelContext into the environment, and any descendant reads it with @Environment(.modelContext) to insert and delete models.

open as a page

In SwiftData, what do @Attribute(.unique) and @Attribute(.externalStorage) change about how a habit's name and photo are stored?

level: middleimportance: must knowfreq 62%

basics

~20 s

@Attribute(.unique) makes the name unique across all Habit records, and saving a duplicate updates the stored record instead of throwing. @Attribute(.externalStorage) asks SwiftData to keep the photo's bytes in a separate file beside the store rather than inside the database.

open as a page

In SwiftData, what do @Relationship's delete rules do, and why does deleting a Project leave its Tasks behind by default?

level: middleimportance: must knowfreq 60%

basics

~20 s

A delete rule says what happens to related models when a model is deleted. The default, .nullify, only clears the tasks' project reference, so the tasks survive as orphans; .cascade on Project.tasks deletes them with the project.

open as a page

Your SwiftData field-inspection app imports 10,000 records from a server while the list stays on screen; why use a @ModelActor rather than mainContext, and how do you build it?

level: seniorimportance: must knowfreq 58%

basics

~20 s

mainContext is @MainActor, so 10,000 inserts and saves on it compete with the UI. A @ModelActor owns its own ModelContext on the same container; pass it the container and Sendable records, insert there and save in batches.

open as a page

In a SwiftUI book list backed by SwiftData's @Query, why can a search field and genre picker in the same view not drive the query, and how do you fix it?

level: seniorimportance: must knowfreq 65%

basics

~20 s

A @Query's filter and sort are fixed when the property is created and cannot read the same view's @State. Keep the inputs in the parent, pass them to a child view, and build the query in its init with _books = Query(filter:sort:).

open as a page

In SwiftData, how do you configure a ModelContainer with ModelConfiguration for an in-memory store, a custom file location or a read-only store?

level: middleimportance: should knowfreq 45%

basics

~10 s

Pass ModelConfiguration values to ModelContainer(for:configurations:). isStoredInMemoryOnly: true keeps the store in memory, the url: initializer places the file, and allowsSave: false makes it read-only; with none, SwiftData builds a default configuration.

open as a page

In SwiftData, when does a ModelContext write changes to the store, and what do autosaveEnabled, save(), hasChanges and rollback() each control?

level: middleimportance: should knowfreq 55%

basics

~20 s

A ModelContext keeps changes in memory until it saves: you call save(), or autosaveEnabled saves for you. Autosave defaults to false and SwiftData turns it on for mainContext; hasChanges reports pending work and rollback() discards it.

open as a page

In SwiftData, which schema changes can a lightweight MigrationStage carry, and which ones need a custom stage?

level: middleimportance: should knowfreq 40%

basics

~20 s

A lightweight SwiftData stage handles added attributes that are optional or have a default, removed attributes, and renames declared with @Attribute(originalName:). Changes that must read and rewrite stored values, such as splitting a field or converting a type, need a custom stage.

open as a page

In SwiftData, how do VersionedSchema and SchemaMigrationPlan fit together, and how does the plan reach the ModelContainer?

level: middleimportance: should knowfreq 38%

basics

~10 s

Each VersionedSchema freezes one shipped shape: a versionIdentifier and the @Model types nested in it. A SchemaMigrationPlan lists those schemas and the MigrationStage between each pair, and you pass it to ModelContainer(for:migrationPlan:configurations:).

open as a page

In a SwiftData @Model class, when do you mark a property @Transient instead of making it computed, and how does SwiftData treat it?

level: middleimportance: should knowfreq 48%

basics

~20 s

Use @Transient for stored state that must not be saved, such as a cached streak; computed properties are never saved anyway. It needs a default unless optional, stays out of the schema, and a freshly fetched instance starts at that default.

open as a page

With SwiftData's FetchDescriptor, how do you page through a large book list and show a total count without loading every Book?

level: middleimportance: should knowfreq 50%

basics

~20 s

Set fetchLimit and fetchOffset on a FetchDescriptor with a stable sort and pass it to the context's fetch(:) for each page. For the badge call fetchCount(:) on a descriptor without a limit, which returns an Int without building any models.

open as a page

In SwiftData, why can a Project's tasks array come back in a different order after relaunch, and how do you keep a user-defined order?

level: middleimportance: should knowfreq 40%

basics

~20 s

SwiftData persists which tasks belong to a project, not the order of the array. Once the models are reloaded from the store, the elements can come back in any order, so store a position on the task and sort by it.

open as a page

In SwiftData, how do you model Tasks that share many Tags, and what happens to a shared Tag when one Task is deleted?

level: middleimportance: should knowfreq 45%

basics

~20 s

Give each model an array of the other and declare @Relationship(inverse:) on one side, because SwiftData does not infer a many-to-many inverse. With the default .nullify rule, deleting a task only removes its links, and the shared tag survives.

open as a page

In SwiftUI with SwiftData, when should a child view receive the model object itself, and when its PersistentIdentifier instead?

level: middleimportance: should knowfreq 38%

basics

~20 s

Within the main-actor view tree, pass the model object: it is an observable reference, so children redraw on change. Pass its PersistentIdentifier when the value must be stored, restored or sent across an actor or context boundary.

open as a page

In SwiftData's modelContainer modifier, what do inMemory, isAutosaveEnabled, isUndoEnabled and onSetup control, and when do you pass your own ModelContainer instead?

level: middleimportance: should knowfreq 48%

basics

~20 s

inMemory (default false) keeps the store off disk, isAutosaveEnabled (true) autosaves the main context, isUndoEnabled (false) binds the window's undo manager to it, and onSetup receives the container or the error. Pass your own instance when several scenes must share it.

open as a page

In SwiftUI with SwiftData, how do you give a #Preview a model container holding sample data, and why should that store live in memory?

level: middleimportance: should knowfreq 50%

basics

~10 s

Build a ModelContainer with ModelConfiguration(isStoredInMemoryOnly: true), insert sample models through its main-actor mainContext, and apply it with modelContainer(_:). In memory, every preview starts from known data and never touches a real store.

open as a page

In SwiftData, why can't a @ModelActor hand a model object to the main actor, and how does PersistentIdentifier let the two sides share it?

level: seniorimportance: should knowfreq 48%

basics

~20 s

@Model classes are deliberately not Sendable, and each belongs to one ModelContext, so Swift 6 rejects returning one across actors. Pass its persistentModelID, a Sendable, Codable PersistentIdentifier, after saving, and load the model again in the receiving context.

open as a page

In SwiftData, a release adds @Attribute(.unique) to Trip.bookingReference, but shipped stores hold duplicates; why does the store fail to open, and how does a custom stage fix it?

level: seniorimportance: should knowfreq 25%

basics

~20 s

A lightweight stage applies the new unique constraint to rows that already collide, so the migration fails and ModelContainer's initializer throws. A custom stage's willMigrate fetches the old Trip type, keeps one trip per reference, removes or merges the rest and saves.

open as a page

After adding a property of a custom struct type, a SwiftData @Model class fails with "no exact matches in call to instance method 'getValue'"; why, and what fixes it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

@Model rewrites each stored property into accessors that call getValue(forKey:) and setValue(forKey:to:), whose overloads need a Codable value, a model or a model collection. A plain struct matches none; make it Codable, or use .transformable(by:) or @Transient.

open as a page

What can SwiftData's #Predicate express, and why does a filter on a computed Book property compile yet fail when the fetch runs?

level: seniorimportance: should knowfreq 55%

basics

~20 s

#Predicate turns a closure into an expression tree that SwiftData translates to a store query. Unsupported calls fail to compile, but a key path to a computed or @Transient property compiles and fails at fetch time: the store has no such column.

open as a page

In SwiftData, a Task has both an assignee and a reviewer of type User; why do the user's task lists stay empty, and how do you declare the inverses?

level: seniorimportance: should knowfreq 35%

basics

~20 s

With two relationships between the same two models, SwiftData cannot tell which property pairs with which, so it infers no inverse and every property stays one-way. Declare each pairing with @Relationship(inverse:) on exactly one side.

open as a page

In SwiftData, when does a fetched Task's related Project load, and why can a task list that shows project names do extra store work?

level: seniorimportance: should knowfreq 30%

basics

~20 s

A fetch of tasks returns the tasks; each task's project is read from the store the first time code accesses that property. A list that shows task.project?.name per row therefore adds store queries per row unless the fetch prefetches the relationship.

open as a page

A SwiftData journal app's entry editor binds a Form to the model with @Bindable, yet tapping Cancel keeps the edits; why, and how do you fix it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

@Bindable bindings write every keystroke straight into the managed model, and the main context autosaves, so dismissing changes nothing. Edit a draft in @State and copy it to the model on Save, or edit in a separate context without autosave.

open as a page

For a SwiftData app about to ship its first release, would you declare a VersionedSchema and SchemaMigrationPlan from day one, or wait for the first change that needs them?

level: principalimportance: should knowfreq 30%

basics

~20 s

Both work: automatic migration covers additive changes without a plan, and a later plan can adopt an unversioned store if its first VersionedSchema matches the shipped models exactly. Day-one versioning records that shape while it is certain, at the cost of frozen types.

open as a page

In SwiftData, a single custom MigrationStage that splits Trip.travelerName into firstName and lastName ends with empty names; why, and what plan keeps the data?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

willMigrate runs while the store has the old shape, before firstName and lastName exist, and didMigrate runs after travelerName is already dropped. Add an intermediate version holding both fields, copy in its didMigrate, then drop travelerName in a lightweight stage.

open as a page

In SwiftData, a habit tracker must keep one CheckIn per habit per day and filter check-ins by date quickly; how do #Unique and #Index express that?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

Declare #Unique<CheckIn>([.habitName, .day]) and #Index<CheckIn>([.day]) inside the model; both arrived in iOS 18. A colliding save updates the stored check-in, and day must hold the start of the day, or every timestamp counts as unique.

open as a page