In SwiftUI with SwiftData, how do you give a #Preview a model container holding sample data, and why should that store live in memory?
answer
- the preview needs its own container
- ModelConfiguration(isStoredInMemoryOnly: true)
- seed through mainContext on the main actor
- modelContainer(_:) on the previewed view
basics
~10 sBuild 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.
solid answer
~40 sA view that uses `@Query` or the environment context needs a container in its preview, exactly as in the app. I keep one helper that builds `ModelContainer(for: Entry.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true))`, inserts three sample entries through `container.mainContext`, which is `@MainActor`, so the helper runs on the main actor, and returns it. The preview applies it with `.modelContainer(SampleJournal.container)`. For an empty state, `.modelContainer(for: Entry.self, inMemory: true)` is enough. The store lives in memory so a preview never reads or writes a real store file: each run starts from exactly the samples I inserted, and seeding cannot pile up duplicates. On iOS 18 and later, a `PreviewModifier` can share that seeded container across many previews.
code
swift · 28 linesimport SwiftUI
import SwiftData
@MainActor
enum SampleJournal {
static let container: ModelContainer = {
do {
let configuration = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(for: Entry.self, configurations: configuration)
for title in ["Morning pages", "Trip to the coast", "Book notes"] {
container.mainContext.insert(Entry(title: title))
}
return container
} catch {
fatalError("Could not build the preview container: \(error)")
}
}()
}
#Preview("Three entries") {
EntryListView()
.modelContainer(SampleJournal.container)
}
#Preview("Empty journal") {
EntryListView()
.modelContainer(for: Entry.self, inMemory: true)
}go deeper
Recall that a SwiftData preview needs its own container and that inMemory: true or isStoredInMemoryOnly: true keeps it off disk.
Explain the seeding recipe: in-memory configuration, inserts through mainContext on the main actor, and modelContainer(_:) on the previewed view.
Argue for determinism: one shared seeded helper, never a real store, and the same fixture reused by unit tests.
Make a shared sample-data container part of the team's preview standard, so every SwiftData screen previews against the same known data.
## Why a preview needs a container at all A SwiftUI preview renders a view outside the running app, so nothing has applied the app's `modelContainer` modifier. A list driven by `@Query`, or an editor that reads `@Environment(\.modelContext)`, then sees the default context Apple documents for that case: one bound to an **in-memory, schema-less container**, where fetches return nothing and inserts fail. The preview must therefore install its own container, and to be useful that container should already hold **sample data**: three journal entries rather than an empty list. ## Building the sample container The recipe has three steps: 1. **Configure an in-memory store** with `ModelConfiguration(isStoredInMemoryOnly: true)` and pass it to `ModelContainer(for:configurations:)`. 2. **Insert sample models** through `container.mainContext`. The `mainContext` property is declared `@MainActor`, so the seeding code must run on the main actor; putting the helper in a `@MainActor` type makes the compiler enforce that. 3. **Apply the container** to the previewed view with `.modelContainer(container)`, the overload that takes an instance. ```swift let configuration = ModelConfiguration(isStoredInMemoryOnly: true) let container = try ModelContainer(for: Entry.self, configurations: configuration) container.mainContext.insert(Entry(title: "Morning pages")) ``` For the empty state, no helper is needed: `.modelContainer(for: Entry.self, inMemory: true)` gives the view a working, empty store, which is exactly what a "No entries yet" placeholder needs. ## Why in memory | Choice | What the preview reads | Risk | |---|---|---| | In-memory store, seeded in code | Only the samples you inserted | None to real data; the store disappears with the container | | On-disk store | Whatever the store file already holds | Seeding again on a store that persisted adds duplicate rows; results drift between runs | | No container at all | The default schema-less context | Empty lists, failing inserts | The point is **determinism**. A preview is a test fixture you look at: the list should show the same three entries every time, in the same order, so that a layout change is the only thing that changes the picture. An in-memory store guarantees the data comes only from the seeding code. It also keeps preview code from ever touching a store file the app or another preview uses, and the same `isStoredInMemoryOnly` configuration doubles as the fixture for unit tests. ## Previewing a view that takes one model An editor or a row takes a single `Entry` rather than querying. Two habits keep those previews honest: - create the sample through the **same seeded container**, so the model belongs to a context exactly as it does at run time, and apply the container to the preview as well, because the editor may read the environment context; - or let the preview query the seeded container and pass the first result down; `@Previewable` lets a `#Preview` body declare that `@Query`, as Apple's `PreviewModifier` example does. ## Making the samples earn their place Sample data is only useful if it exercises the layout the way real data will. A few habits pay off: - include an **edge case** per field: a long title that must truncate, an entry with empty text, dates far apart so sorting is visible; - insert **related models through the root**: Apple's `ModelContext` documentation says inserting the root of a graph of related models inserts the related ones too, so one `insert` of an entry with its tags is enough; - keep sample values as **static factories on a preview-only type**, so the app target never ships them by accident. ## Sharing the seeded container When many previews need the same data, a **`PreviewModifier`** (iOS 18 and later) can build the container once in `makeSharedContext()` and apply it in `body(content:context:)` with `.modelContainer(context)`; the preview system caches that shared context across the previews that use the modifier through the `.modifier` trait. Before iOS 18, a static property on a `@MainActor` helper type does a similar job. ## Common mistakes - Seeding through a background context, or off the main actor: `mainContext` is main-actor isolated, and the compiler says so. - Copying the preview's `inMemory: true` into the app's scene, so the shipping app forgets everything on each launch. - Building a new seeded container inside every preview body when one shared helper would keep the samples consistent. - Mixing the samples into production code paths rather than keeping them in preview-only helpers.
- Why is the sample-data helper marked @MainActor?`ModelContainer.mainContext` is declared `@MainActor`, so inserting through it must happen on the main actor. Marking the helper type `@MainActor` lets the compiler check that, and `#Preview` bodies already run there, so the preview can read the static container directly.
- Can the same in-memory setup serve unit tests?Yes. A `ModelConfiguration(isStoredInMemoryOnly: true)` container gives each test a fresh store that starts with only the models the test inserts, and Apple's documentation names tests as a use for in-memory storage. Build a new container per test rather than sharing one, so tests cannot see each other's rows.
- A preview can rely on the app's own container being installed.
- Seeding sample data can happen from any thread or actor.
- allowsSave: false is what keeps a preview store in memory.
- A preview without modelContainer gets an empty but working store.
- Sample data belongs in the app's launch path so previews can see it.