SwiftData Expert Skill
Overview
Use this skill to build, review, and harden SwiftData persistence architecture with Apple-documented patterns from iOS 17 through current updates. Prioritize data integrity, migration safety, sync correctness, and predictable concurrency behavior.
Agent Behavior Contract (Follow These Rules)
- Identify the minimum deployment target before recommending APIs (notably
#Index, #Unique, HistoryDescriptor, DataStore, inheritance examples).
- Confirm the app has real
ModelContainer wiring before debugging data issues; without it, inserts fail and fetches are empty.
- Distinguish main-actor UI operations from background persistence operations; never assume one context fits both.
- Treat schema changes as migration changes: evaluate lightweight migration first, then
SchemaMigrationPlan when needed.
- For CloudKit-enabled apps, verify schema compatibility constraints before proposing model changes.
- Prefer deterministic query definitions (shared predicates, explicit sort order, bounded fetches) over ad hoc filtering in views.
- Use persistent history tokens when reading cross-process changes; delete stale history to avoid storage growth.
- In code reviews, prioritize data loss risk, accidental mass deletion, sync divergence, and context-isolation bugs over style changes.
Analysis Commands (Use Early)
- Search container setup:
rg "modelContainer\\(|ModelContainer\\(" -n
- Search model definitions:
rg "^@Model|#Unique|#Index|@Relationship|@Attribute|@Transient" -n
- Search context usage:
rg "modelContext|mainContext|ModelContext\\(" -n
- Search migrations and history:
rg "SchemaMigrationPlan|VersionedSchema|MigrationStage|fetchHistory|deleteHistory|historyToken" -n
- Search CloudKit and app groups:
rg "cloudKitDatabase|iCloud|CloudKit|groupContainer|AppGroup|NSPersistentCloudKitContainer" -n
Project Intake (Before Advising)
- Determine deployment targets: iOS, iPadOS, macOS, watchOS, and visionOS.
- Locate container setup:
.modelContainer(...) modifier or manual ModelContainer(...).
- Verify whether autosave is expected and whether explicit
save() is required.
- Check if undo is enabled (
isUndoEnabled) and whether operations occur on mainContext or custom contexts.
- Check CloudKit capabilities and chosen container strategy (
automatic, .private(...), .none).
- Check if app group storage is required.
- Check if Core Data coexistence is in scope.
- Check if schema changes must be backward-compatible with existing user data.
Workflow Decision Tree
- Need a new model or schema shape:
- Read
references/modeling-and-schema.md.
- Need create, update, delete behavior or context correctness:
- Read
references/model-context-and-lifecycle.md.
- Need filtering, sorting, or dynamic list behavior:
- Read
references/querying-and-fetching.md.
- Need relationship modeling or inheritance:
- Read
references/relationships-and-inheritance.md.
- Need migration planning, release upgrades, or change tracking:
- Read
references/migrations-and-history.md.
- Need iCloud sync or CloudKit compatibility:
- Read
references/cloudkit-sync.md.
- Need incremental migration from Core Data:
- Read
references/core-data-adoption.md.
- Need background isolation or actor-based persistence:
- Read
references/concurrency-and-actors.md.
- Need quick diagnostics or API availability checks:
- Read
references/troubleshooting-and-updates.md.
- Need end-to-end execution playbook for a concrete task:
- Read
references/implementation-playbooks.md.
Triage-First Playbook (Common Problems -> Next Move)
- Insert fails or fetch is always empty:
- Confirm
.modelContainer(...) is attached at app or window root and the model type is included.
- Duplicate rows appear after network refresh:
- Add
@Attribute(.unique) or #Unique constraints and rely on insert-upsert behavior.
- Unexpected data loss during delete:
- Audit delete rules (
.cascade vs .nullify) and check for unbounded delete(model:where:).
- Undo or redo does nothing:
- Ensure
isUndoEnabled: true and that changes are saved via mainContext (not only background context).
- CloudKit sync not behaving:
- Check capabilities, remote notifications, and CloudKit schema compatibility; explicitly set
cloudKitDatabase if multiple containers exist.
- Widget or App Intent changes are not reflected:
- Use persistent history (
fetchHistory) with token + author filtering.
historyTokenExpired appears:
- Reset local token strategy and rebootstrap change consumption from a safe point.
- Query results are expensive or unstable:
- Use shared predicate builders, explicit sorting, and bounded
FetchDescriptor settings.
Anti-Patterns (Reject by Default)
- Building persistence logic before validating container wiring.
- Performing broad deletes without predicate review and confirmation.
- Mixing UI-driven editing and background write pipelines without isolation boundaries.
- Relying on ad hoc in-memory filtering instead of store-backed predicates.
- Enabling CloudKit sync without capability setup and schema compatibility checks.
- Shipping schema changes without migration rehearsal on existing user data.
- Consuming history without token persistence and cleanup policy.
Core Patterns
App-level container wiring (SwiftUI)
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
RootView()
}
.modelContainer(for: [Trip.self, Accommodation.self])
}
}
Manual container configuration
let config = ModelConfiguration(isStoredInMemoryOnly: false)
let container = try ModelContainer(
for: Trip.self,
Accommodation.self,
configurations: config
)
Dynamic query setup in a view initializer
struct TripListView: View {
@Query private var trips: [Trip]
init(searchText: String) {
let predicate = #Predicate<Trip> {
searchText.isEmpty || $0.name.localizedStandardContains(searchText)
}
_trips = Query(filter: predicate, sort: \.startDate, order: .forward)
}
var body: some View { List(trips) { Text($0.name) } }
}
Safe batch delete pattern
do {
try modelContext.delete(
model: Trip.self,
where: #Predicate { $0.endDate < .now },
includeSubclasses: true
)
try modelContext.save()
} catch {
// Handle delete and save failures.
}
Reference Files
references/modeling-and-schema.md
references/model-context-and-lifecycle.md
references/querying-and-fetching.md
references/relationships-and-inheritance.md
references/migrations-and-history.md
references/cloudkit-sync.md
references/core-data-adoption.md
references/concurrency-and-actors.md
references/troubleshooting-and-updates.md
references/implementation-playbooks.md
Best Practices Summary
- Keep model code as the source of truth; avoid hidden schema assumptions.
- Apply explicit uniqueness and indexing strategy for large or frequently queried datasets.
- Insert root models and let SwiftData traverse relationship graphs automatically.
- Keep query behavior deterministic with explicit predicates and sort descriptors.
- Bound fetches (
fetchLimit, offsets, identifier-only fetches) for scalability.
- Treat delete rules as business rules; review them during schema changes.
- Use
ModelConfiguration for environment-specific behavior (in-memory tests, CloudKit, app groups, read-only stores).
- Handle history as an operational system: token persistence, filtering, and cleanup.
- Use model actors or isolated contexts for non-UI persistence work.
- Gate recommendations by API availability and deployment target.
Verification Checklist (After Changes)
- Build succeeds for target platforms and minimum deployment versions.
- CRUD tests pass with real store and in-memory store.
- Relationship deletes behave as intended (
cascade, nullify, and others).
- Query behavior is stable with realistic datasets and sort or filter combinations.
- Migration path is validated on pre-existing data (not only clean installs).
- CloudKit behavior is validated in a development container before release.
- Cross-process changes (widgets, intents, extensions) are observed correctly.
- Error paths and rollback behavior are covered for destructive operations.
Response Contract
- For review tasks, report findings first by severity and include exact file paths and lines.
- For implementation tasks, describe:
- container or context changes,
- schema or migration changes,
- query or performance changes,
- verification steps run and any gaps.
- If deployment target blocks a recommended API, provide the best fallback compatible with the current target.
1---2name: swiftdata-expert-skill3description: Expert guidance for designing, implementing, migrating, and debugging SwiftData persistence in Swift and SwiftUI apps. Use when working with @Model schemas, @Relationship/@Attribute rules, Query or FetchDescriptor data access, ModelContainer/ModelContext configuration, CloudKit sync, SchemaMigrationPlan/history APIs, ModelActor concurrency isolation, or Core Data to SwiftData adoption/coexistence.4---56# SwiftData Expert Skill78## Overview910Use this skill to build, review, and harden SwiftData persistence architecture with Apple-documented patterns from iOS 17 through current updates. Prioritize data integrity, migration safety, sync correctness, and predictable concurrency behavior.1112## Agent Behavior Contract (Follow These Rules)13141. Identify the minimum deployment target before recommending APIs (notably `#Index`, `#Unique`, `HistoryDescriptor`, `DataStore`, inheritance examples).152. Confirm the app has real `ModelContainer` wiring before debugging data issues; without it, inserts fail and fetches are empty.163. Distinguish main-actor UI operations from background persistence operations; never assume one context fits both.174. Treat schema changes as migration changes: evaluate lightweight migration first, then `SchemaMigrationPlan` when needed.185. For CloudKit-enabled apps, verify schema compatibility constraints before proposing model changes.196. Prefer deterministic query definitions (shared predicates, explicit sort order, bounded fetches) over ad hoc filtering in views.207. Use persistent history tokens when reading cross-process changes; delete stale history to avoid storage growth.218. In code reviews, prioritize data loss risk, accidental mass deletion, sync divergence, and context-isolation bugs over style changes.2223## Analysis Commands (Use Early)2425- Search container setup:26 - `rg "modelContainer\\(|ModelContainer\\(" -n`27- Search model definitions:28 - `rg "^@Model|#Unique|#Index|@Relationship|@Attribute|@Transient" -n`29- Search context usage:30 - `rg "modelContext|mainContext|ModelContext\\(" -n`31- Search migrations and history:32 - `rg "SchemaMigrationPlan|VersionedSchema|MigrationStage|fetchHistory|deleteHistory|historyToken" -n`33- Search CloudKit and app groups:34 - `rg "cloudKitDatabase|iCloud|CloudKit|groupContainer|AppGroup|NSPersistentCloudKitContainer" -n`3536## Project Intake (Before Advising)3738- Determine deployment targets: iOS, iPadOS, macOS, watchOS, and visionOS.39- Locate container setup: `.modelContainer(...)` modifier or manual `ModelContainer(...)`.40- Verify whether autosave is expected and whether explicit `save()` is required.41- Check if undo is enabled (`isUndoEnabled`) and whether operations occur on `mainContext` or custom contexts.42- Check CloudKit capabilities and chosen container strategy (`automatic`, `.private(...)`, `.none`).43- Check if app group storage is required.44- Check if Core Data coexistence is in scope.45- Check if schema changes must be backward-compatible with existing user data.4647## Workflow Decision Tree48491. Need a new model or schema shape:50 - Read `references/modeling-and-schema.md`.512. Need create, update, delete behavior or context correctness:52 - Read `references/model-context-and-lifecycle.md`.533. Need filtering, sorting, or dynamic list behavior:54 - Read `references/querying-and-fetching.md`.554. Need relationship modeling or inheritance:56 - Read `references/relationships-and-inheritance.md`.575. Need migration planning, release upgrades, or change tracking:58 - Read `references/migrations-and-history.md`.596. Need iCloud sync or CloudKit compatibility:60 - Read `references/cloudkit-sync.md`.617. Need incremental migration from Core Data:62 - Read `references/core-data-adoption.md`.638. Need background isolation or actor-based persistence:64 - Read `references/concurrency-and-actors.md`.659. Need quick diagnostics or API availability checks:66 - Read `references/troubleshooting-and-updates.md`.6710. Need end-to-end execution playbook for a concrete task:68 - Read `references/implementation-playbooks.md`.6970## Triage-First Playbook (Common Problems -> Next Move)7172- Insert fails or fetch is always empty:73 - Confirm `.modelContainer(...)` is attached at app or window root and the model type is included.74- Duplicate rows appear after network refresh:75 - Add `@Attribute(.unique)` or `#Unique` constraints and rely on insert-upsert behavior.76- Unexpected data loss during delete:77 - Audit delete rules (`.cascade` vs `.nullify`) and check for unbounded `delete(model:where:)`.78- Undo or redo does nothing:79 - Ensure `isUndoEnabled: true` and that changes are saved via `mainContext` (not only background context).80- CloudKit sync not behaving:81 - Check capabilities, remote notifications, and CloudKit schema compatibility; explicitly set `cloudKitDatabase` if multiple containers exist.82- Widget or App Intent changes are not reflected:83 - Use persistent history (`fetchHistory`) with token + author filtering.84- `historyTokenExpired` appears:85 - Reset local token strategy and rebootstrap change consumption from a safe point.86- Query results are expensive or unstable:87 - Use shared predicate builders, explicit sorting, and bounded `FetchDescriptor` settings.8889## Anti-Patterns (Reject by Default)9091- Building persistence logic before validating container wiring.92- Performing broad deletes without predicate review and confirmation.93- Mixing UI-driven editing and background write pipelines without isolation boundaries.94- Relying on ad hoc in-memory filtering instead of store-backed predicates.95- Enabling CloudKit sync without capability setup and schema compatibility checks.96- Shipping schema changes without migration rehearsal on existing user data.97- Consuming history without token persistence and cleanup policy.9899## Core Patterns100101### App-level container wiring (SwiftUI)102103```swift104@main105struct MyApp: App {106 var body: some Scene {107 WindowGroup {108 RootView()109 }110 .modelContainer(for: [Trip.self, Accommodation.self])111 }112}113```114115### Manual container configuration116117```swift118let config = ModelConfiguration(isStoredInMemoryOnly: false)119let container = try ModelContainer(120 for: Trip.self,121 Accommodation.self,122 configurations: config123)124```125126### Dynamic query setup in a view initializer127128```swift129struct TripListView: View {130 @Query private var trips: [Trip]131132 init(searchText: String) {133 let predicate = #Predicate<Trip> {134 searchText.isEmpty || $0.name.localizedStandardContains(searchText)135 }136 _trips = Query(filter: predicate, sort: \.startDate, order: .forward)137 }138139 var body: some View { List(trips) { Text($0.name) } }140}141```142143### Safe batch delete pattern144145```swift146do {147 try modelContext.delete(148 model: Trip.self,149 where: #Predicate { $0.endDate < .now },150 includeSubclasses: true151 )152 try modelContext.save()153} catch {154 // Handle delete and save failures.155}156```157158## Reference Files159160- `references/modeling-and-schema.md`161- `references/model-context-and-lifecycle.md`162- `references/querying-and-fetching.md`163- `references/relationships-and-inheritance.md`164- `references/migrations-and-history.md`165- `references/cloudkit-sync.md`166- `references/core-data-adoption.md`167- `references/concurrency-and-actors.md`168- `references/troubleshooting-and-updates.md`169- `references/implementation-playbooks.md`170171## Best Practices Summary1721731. Keep model code as the source of truth; avoid hidden schema assumptions.1742. Apply explicit uniqueness and indexing strategy for large or frequently queried datasets.1753. Insert root models and let SwiftData traverse relationship graphs automatically.1764. Keep query behavior deterministic with explicit predicates and sort descriptors.1775. Bound fetches (`fetchLimit`, offsets, identifier-only fetches) for scalability.1786. Treat delete rules as business rules; review them during schema changes.1797. Use `ModelConfiguration` for environment-specific behavior (in-memory tests, CloudKit, app groups, read-only stores).1808. Handle history as an operational system: token persistence, filtering, and cleanup.1819. Use model actors or isolated contexts for non-UI persistence work.18210. Gate recommendations by API availability and deployment target.183184## Verification Checklist (After Changes)185186- Build succeeds for target platforms and minimum deployment versions.187- CRUD tests pass with real store and in-memory store.188- Relationship deletes behave as intended (`cascade`, `nullify`, and others).189- Query behavior is stable with realistic datasets and sort or filter combinations.190- Migration path is validated on pre-existing data (not only clean installs).191- CloudKit behavior is validated in a development container before release.192- Cross-process changes (widgets, intents, extensions) are observed correctly.193- Error paths and rollback behavior are covered for destructive operations.194195## Response Contract196197- For review tasks, report findings first by severity and include exact file paths and lines.198- For implementation tasks, describe:199 - container or context changes,200 - schema or migration changes,201 - query or performance changes,202 - verification steps run and any gaps.203- If deployment target blocks a recommended API, provide the best fallback compatible with the current target.