In SwiftUI with SwiftData, when should a child view receive the model object itself, and when its PersistentIdentifier instead?
answer
- inside the view tree versus across a boundary
- models are Observable references
- let for reading, @Bindable for editing
- @SceneStorage of a PersistentIdentifier
- a model's id is a PersistentIdentifier
basics
~20 sWithin 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.
solid answer
~50 sInside the SwiftUI tree I pass the model itself: `let entry: Entry` for a view that only reads it, `@Bindable var entry: Entry` when it needs bindings. Because `@Model` makes the class `Observable`, the child redraws when the properties it reads change, and there is no copy to keep in sync. I switch to the `PersistentIdentifier` when the value leaves the tree's lifetime or isolation: selection that must survive scene restoration (SwiftData adds `@SceneStorage` and `@AppStorage` initializers for `PersistentIdentifier` since iOS 17), a value that crosses to another actor or another context, or anything I encode. The identifier is `Codable`, `Hashable` and `Sendable`, and a model's `id` has that type, so it also works as a `List` selection. I resolve it back through what I already queried, or the context, and treat a missing entry as no selection.
code
swift · 32 linesimport SwiftUI
import SwiftData
struct JournalSplitView: View {
@Query(sort: \Entry.createdAt, order: .reverse) private var entries: [Entry]
@SceneStorage("selectedEntry") private var selectedID: PersistentIdentifier?
var body: some View {
NavigationSplitView {
List(entries, selection: $selectedID) { entry in
Text(entry.title)
}
} detail: {
if let entry = entries.first(where: { $0.id == selectedID }) {
EntryDetailView(entry: entry)
} else {
Text("Select an entry")
}
}
}
}
struct EntryDetailView: View {
let entry: Entry
var body: some View {
ScrollView {
Text(entry.text)
}
.navigationTitle(entry.title)
}
}go deeper
Recall that a child view can take the SwiftData model directly with let, and uses @Bindable only when it needs bindings.
Explain why observation makes passing the model enough, and where PersistentIdentifier fits: storage, selection and actor hand-offs.
Show restoration with @SceneStorage of a PersistentIdentifier, resolving it back safely when the entry has been deleted.
Set the convention that identifiers live at boundaries and models flow through the view tree, so restoration and background work stay consistent.
## Two ways to point at a stored entry A SwiftData model object is a **reference type** that a `ModelContext` tracks. Every model also has a **`persistentModelID`**, a `PersistentIdentifier` value that names the stored record. The `id` that `PersistentModel` supplies for `Identifiable` is of the same type, so `ForEach` and `List` identify rows by a `PersistentIdentifier`. A child view can be given either one, and the choice is about **boundaries**, not style. | Pass | Good for | Avoid when | |---|---|---| | The model object (`let entry: Entry`) | Displaying it in a child view on the main actor | The value must outlive the view tree or cross an actor | | The model with `@Bindable var entry: Entry` | Child views that need bindings for controls | The editor needs Cancel to discard edits | | `PersistentIdentifier` | Selection, restoration, encoding, handing work to another actor or context | A plain child view that just shows the entry | ## Inside the view tree: pass the model Views run on the main actor, and so does the environment context that produced the model. Handing the object down is the natural choice: - **Observation does the work.** `@Model` adds `Observable` conformance, so a child that reads `entry.title` in `body` is redrawn when that property changes. No wrapper is needed just to observe; `let entry: Entry` is enough. - **`@Bindable` is for bindings only.** Add it when the child hands `$entry.title` to a `TextField`; it is not required for display. - **No re-fetch.** A child that receives an identifier and fetches the model again adds code and a lookup for no gain. ## When the identifier wins 1. **Restoring selection.** Scene storage and app storage only hold simple values, but SwiftData's SwiftUI layer adds initializers to both `@SceneStorage` and `@AppStorage` for `PersistentIdentifier` and `PersistentIdentifier?` (iOS 17). A split view can keep `@SceneStorage("selectedEntry") var selectedID: PersistentIdentifier?` and restore the open entry after the system relaunches the scene. 2. **Selection bindings.** Because the model's `id` is a `PersistentIdentifier`, `List(entries, selection: $selectedID)` works with a `PersistentIdentifier?` binding directly. 3. **Crossing an actor or context.** A background importer on its own actor, or a scratch context used for a draft editor, should receive identifiers and load the model in its own context; model objects stay with the context that fetched them. The compiler enforces this: passing an `@Model` object where `Sendable` is required reports that "PersistentModels are not Sendable" and suggests a model actor or the model's `persistentModelID`, a warning in the Swift 5 language mode and an error in Swift 6. The identifier itself is `Sendable` and `Codable`. 4. **Encoding.** Anything written out locally, such as restoration state, should store identifiers rather than titles or indexes that change. Apple's documentation notes that a `persistentModelID` is only relevant within the scope of the local data store, so it is not an identity to send to a server or another device. ## Resolving an identifier back Turning an identifier into a model is cheap when the parent already holds the queried array: find the element whose `id` matches. Otherwise ask the context, with `model(for:)` or a fetch filtered on the identifier. Either way, plan for the record being gone: - the entry may have been deleted in another window since the selection was saved; - treat an identifier that matches nothing as **no selection**, and show the placeholder instead of crashing on a force-unwrap. ## A model can disappear under a child Passing the model object is not a promise that it lives forever. Another window, a sync or a swipe-to-delete in the sidebar can delete the entry while a detail view still holds it. `PersistentModel` exposes an **`isDeleted`** property, and a detail view that receives its model by lookup, as below, simply stops being shown when the lookup finds nothing. Holding a model in long-lived state outside the view tree, such as a singleton, is where stale references linger; holding its identifier there and resolving it on demand avoids that. ## A worked example In the journal app, the sidebar lists entries from `@Query`, the selection is a `PersistentIdentifier?` held in `@SceneStorage`, and the detail column receives the **model**, looked up from the queried array: ```swift if let entry = entries.first(where: { $0.id == selectedID }) { EntryDetailView(entry: entry) } ``` Identifiers live at the edges (storage, selection, actor hand-offs) and model objects flow through the middle, where observation keeps every child current.
- Why can't @SceneStorage hold the Entry itself?Scene storage persists small values the system can restore with the scene, not live reference types. SwiftData's SwiftUI layer adds `@SceneStorage` and `@AppStorage` initializers for `PersistentIdentifier` and its optional form, so you store the identifier and look the entry up again after restoration.
- What should the detail view show if the stored identifier no longer matches an entry?The empty-selection placeholder. The entry may have been deleted in another window or on another launch, so resolving the identifier must handle no match, as `first(where:)` returning `nil` does, rather than force-unwrapping.
- Child views should get identifiers and refetch; model objects are unsafe in views.
- A child needs @Bindable just to display a model's properties.
- @SceneStorage only holds strings, so store the entry's title instead.
- A view can hand its model object to a background actor safely.
- A child must copy the model into @State to see its changes.