SwiftData with Claude Code, Cursor and Codex: skills, rules and iOS 27 APIs
Install a SwiftData skill such as SwiftData Pro so the agent stops guessing at APIs. Tell it your deployment target, because iOS 27 adds ResultsObserver, HistoryObserver and sectioned queries. Keep a ModelContext on one actor and pass PersistentIdentifiers instead, plan migrations with VersionedSchema, follow CloudKit's limits, and test against an in-memory ModelContainer.
Last updated:
This page is about getting a coding agent (Claude Code, Cursor, Codex, or the agents inside Xcode) to write SwiftData code that compiles, stays thread-safe, migrates and syncs. For Swift concurrency in general, see Swift 6 concurrency with AI agents. For setting up agents inside Xcode, see Agents inside Xcode 27.
Why agents get SwiftData wrong
SwiftData changes every June, and a model's training data lags behind. Apple's SwiftData updates page lists new APIs in 2024 (#Index, #Unique, persistent history, custom data stores), in 2025 (model inheritance) and again in June 2026. An agent that doesn't know your deployment target will either miss the new APIs or use them where they don't exist. Two fixes, and you want both:
Install a SwiftData skill (table below). Skills are loaded only when the task needs them and carry the rules the model lacks. The SwiftData Pro README says it targets "the mistakes LLMs actually make".
Put your deployment target and persistence rules in
AGENTS.mdorCLAUDE.md, for example "iOS 18 minimum, SwiftData only, no Core Data, CloudKit private database". Then the agent knows which of the rules below apply.
Model rules to give the agent
From Apple's article "Preserving your app's model data across launches" and the API reference:
@Modelmakes a class persistable and addsPersistentModelandObservableconformance. SwiftData stores all noncomputed properties of compatible types: primitives such asBool,IntandString, and value types that conform toCodable.@Attributechanges how one property is stored:.unique, preserving the value after deletion, Spotlight indexing, encryption, andoriginalNameto keep data when you rename a property.@Relationshipsets the delete rule; Apple's example uses.cascadeso related models are deleted with their parent. Mark temporary properties with@Transientso they aren't saved.Indexes and compound uniqueness:
#Index(iOS 18 and later) defines individual and compound indexes for faster sorts and predicate fetches,#Unique(iOS 18 and later) treats a tuple of attributes as unique, and since June 2024inverse: nilmakes a relationship unidirectional.Inheritance (from June 2025): subclass a
@Modelclass only for real "is a" hierarchies. Apple advises against it when subclasses would share just one property, or when most queries run across all types; then an enum or a Bool property is simpler. Predicates can check the type with$0 is BusinessTrip.Container setup:
.modelContainer(for: [Trip.self, Accommodation.self])at the top of the SwiftUI hierarchy, orModelContainer(for:)without SwiftUI. Apple notes that automatic iCloud sync uses the first container in your CloudKit entitlement.
Concurrency: what may cross actors
This is where agents produce the most compile errors under Swift 6. Apple's API reference states the conformances:
| Type | Sendable? | What to do |
|---|---|---|
ModelContainer | Yes | Pass it to background work and create a context there |
PersistentIdentifier | Yes (also Codable, Hashable) | Pass IDs between actors, fetch the model again on the other side |
ModelContext | No | Keep each context on one actor; use container.mainContext on the main actor |
@Model instances (PersistentModel) | No | Don't hand them to another actor; refetch by ID |
For background imports, ask for a model actor: the ModelActor protocol inherits from Actor, and the @ModelActor macro "converts a Swift actor into a model actor by generating boilerplate code". A rule for AGENTS.md:
SwiftData: never pass a
ModelContextor a@Modelinstance across actors. Pass theModelContainerorPersistentIdentifiers and do background work in a@ModelActor.
Everything beyond that (strict concurrency, @MainActor defaults, Sendable audits) belongs in Swift 6 concurrency with AI agents.
Migrations: make the agent write a plan
Agents often change a model and hope the store opens. Ask for an explicit plan instead:
Describe each shipped schema as a
VersionedSchema("a specific version of a schema, including the models it contains").Describe how to get from one to the next in a
SchemaMigrationPlan, made ofMigrationStagevalues:.lightweight(fromVersion:toVersion:)for changes SwiftData can infer,.custom(fromVersion:toVersion:willMigrate:didMigrate:)when you need to transform data.Pass the plan with
ModelContainer(for:migrationPlan:configurations:).For a renamed property,
@Attribute(originalName:)keeps existing data.
A prompt that works well: "Before changing any @Model, copy the current models into SchemaV2, add a MigrationStage, and tell me whether it is lightweight or custom and why."
CloudKit sync: the limits agents forget
Apple's article "Syncing model data across devices" lists what CloudKit can't do:
No unique constraints: CloudKit can't enforce
.unique, so@Attribute(.unique)and#Uniquedon't fit synced models.All relationships optional, and set the inverse explicitly if SwiftData can't infer it.
No
denydelete rule.Additive-only schemas: after you promote the schema to production you can't delete model types or change existing attributes.
Setup steps from the same article: the iCloud capability with CloudKit and a container, Background Modes with Remote notifications, and, during development, initializing the CloudKit schema in a #if DEBUG block with initializeCloudKitSchema(). Pick the database with ModelConfiguration(cloudKitDatabase: .private("iCloud.com.example.Trips")), or pass .none to opt a store out of sync. Configuring the iCloud capability needs an active developer account with admin permissions, so an agent can write the code but you may have to click through the capability yourself.
New in iOS 27: tell the agent explicitly
Apple's SwiftData updates page (June 2026) lists four additions, all available from iOS 27 and macOS 27:
Sectioned queries: query macros that take a
sectionByparameter (listed under Additional query macros).@Attribute(.codable): stores a property through its Codable representation, including types you don't control.ResultsObserver: an observable collection of results that match fetch criteria and update in real time, also when another context or CloudKit sync changes the data. Apple's example:ResultsObserver<Book, Never>(filterBy: #Predicate { $0.isPublished }, sortBy: [SortDescriptor(\.title)], modelContext: context), andsectionBy: \.genrefor sections.HistoryObserver: listens for the container's remote-change notifications and bumps aneventCounteryou can observe in SwiftUI; scope it withobservedModels.
If your app still supports iOS 26 or earlier, ask the agent to wrap these in if #available(iOS 27, *) and keep a fallback, or it will happily use them everywhere.
Testing the persistence layer
Apple names tests as the reason to keep storage in memory: ModelConfiguration(isStoredInMemoryOnly: true) on a fresh ModelContainer. Rules worth giving the agent:
One new in-memory container per test, so tests don't share state.
Test
@ModelActorcode through the actor's own methods instead of reaching into its context.Keep ViewModel tests free of SwiftData with a mock repository; that is the pattern the SwiftData Testing skill teaches.
For UI tests that drive the simulator, see iOS UI testing with AI agents.
SwiftData tools for agents compared
| Tool / skill | What it does (from README) | Agents | Install (from README) | License | ★ (26 Oct) | Last push |
|---|---|---|---|---|---|---|
| SwiftData Pro (twostraws) | Rules for @Model, @Query, predicates, indexes, migrations, relationships and iCloud sync, aimed at the mistakes LLMs make; designed for iOS 26+ and Swift 6.2+ | Claude Code, Codex, Cursor, Gemini | /plugin marketplace add twostraws/SwiftData-Agent-Skill, /plugin install swiftdata-pro@swiftdata-agent-skill, or npx skills add https://github.com/twostraws/swiftdata-agent-skill --skill swiftdata-pro | MIT | 452 | 19 Oct 2026 |
| SwiftData Expert (vanab) | Container and configuration strategy, ModelContext and @ModelActor isolation, identifier hand-off, FetchDescriptor tuning, VersionedSchema migrations, persistent history, CloudKit constraints, Core Data coexistence | Any Agent Skills tool | npx skills add https://github.com/vanab/SwiftData-agent-skill --skill swiftdata-expert-skill | MIT | 14 | 8 Feb 2026 ⚠ |
| SwiftData Testing (akshaypimprikar) | Test patterns only: in-memory ModelContainer fixtures, mock repositories for ViewModel tests, @ModelActor test isolation, Decimal assertions, import dedup tests | Claude Code, Codex, Cursor, Gemini | git clone https://github.com/akshaypimprikar/ios-swiftdata-testing-agent-skill.git, then cp -r ios-swiftdata-testing-agent-skill/swiftdata-testing ~/.claude/skills/ | MIT | 4 | 19 Jul 2026 ⚠ |
| Core Data Expert (AvdLee) | Core Data stack setup, thread safety with NSManagedObjectID, batching and faulting, schema migration, CloudKit sync | Any Agent Skills tool (Claude Code plugin, Codex, Cursor) | npx skills add https://github.com/avdlee/core-data-agent-skill --skill core-data-expert | MIT | 318 | 14 Sep 2026 ⚠ |
| Swift Skills Pro (laxrajpurohit) | 12 skills for Swift 6 / iOS 26, including swiftdata-pro (@Model, @Query, migrations, CloudKit sync) and core-data-pro; wrong/right examples and a mistakes checklist per skill | Claude Code, Codex, Cursor, Windsurf | /plugin marketplace add laxrajpurohit/swift-skills-pro, /plugin install swiftdata-pro@swift-skills-pro, or npx swift-skills-cli install | MIT | 6 | 18 Oct 2026 |
| SQLiteData Skills (sitapix) | Seven skills for Point-Free's SQLiteData, the GRDB-based alternative to SwiftData: @Table, @FetchAll, migrations, CloudKit SyncEngine and sharing, diagnostics, and migrating from SwiftData | Claude Code, any agent via skills CLI | npx skills add sitapix/sqlitedata-swift-skills | MIT | 0 | 29 Apr 2026 ⚠ |
⚠ = no push for more than 4 weeks. SwiftData Expert was last updated on 8 Feb 2026 and SQLiteData Skills on 29 Apr 2026 (last push); check them against your iOS version. SwiftData Pro and Swift Skills Pro both name a skill swiftdata-pro; install only one of them in the same project. Several general iOS skill packs also include SwiftData rules; see /categories/swiftdata.
Which one to pick:
Most projects: SwiftData Pro. Add SwiftData Testing when the agent writes your persistence tests.
You want the agent to reason about isolation, history and CloudKit at length: SwiftData Expert, checked against the iOS 27 changes above since it predates them.
One install for SwiftData plus SwiftUI, concurrency and testing rules: Swift Skills Pro (instead of SwiftData Pro, because of the shared skill name).
Still on Core Data, or migrating from it: Core Data Expert.
You chose SQLiteData instead of SwiftData: SQLiteData Skills.
A prompt that keeps the agent honest
Use the SwiftData skill. Our minimum is iOS 18. Add a
Tagmodel with a many-to-many relationship toNote. Keep it CloudKit-compatible (optional relationships, no unique constraints), add aSchemaV3with a lightweightMigrationStage, do the import in a@ModelActor, and write tests against an in-memory container. Don't use iOS 27 APIs without an availability check.
FAQ
- Which SwiftData skill should I install for Claude Code?
- SwiftData Pro by twostraws is the most-starred SwiftData skill in our catalog: it targets the SwiftData mistakes LLMs make (models, queries, predicates, indexes, migrations, relationships, iCloud sync) and installs as a Claude Code plugin or with npx skills add for Cursor, Codex and Gemini. Add SwiftData Testing if the agent also writes your persistence tests.
- Can I pass a SwiftData model or ModelContext to another actor?
- Not safely. In Apple's documentation, ModelContainer and PersistentIdentifier conform to Sendable, but ModelContext and model instances (PersistentModel) do not. Pass the container or the identifier across the boundary and do background work in a model actor; the @ModelActor macro generates the boilerplate for one.
- What is new in SwiftData in iOS 27?
- Apple's SwiftData updates page for June 2026 lists four changes: queries sectioned with a sectionBy parameter, a codable option for Attribute that stores Codable types including ones you don't control, ResultsObserver for live results that match fetch criteria, and HistoryObserver for remote model changes. Apple's docs list them as available from iOS 27 and macOS 27.
- Why does my SwiftData model break CloudKit sync?
- CloudKit doesn't support every SwiftData feature. Apple lists the limits: no unique constraints, all relationships must be optional, set the inverse explicitly when SwiftData can't infer it, and no deny delete rule. CloudKit schemas are additive only once promoted to production, so you can't delete model types or change existing attributes afterwards.
- How should an agent test SwiftData code?
- Use a ModelContainer whose ModelConfiguration stores data in memory only; Apple names running tests as the use case. Build a fresh container per test so state doesn't leak between tests, and keep ViewModel tests free of SwiftData with mock repositories, which is the pattern the SwiftData Testing skill teaches.