- You’ll want to download the sample app from here. Make sure to change the group and application identifier
- You get undo and autosave when you switch applications. Works with your basic classes and structs
- It uses a new @Model macro
- Where possible SwiftData will infer structure from your code, but you can be very explicit – check out Model your Schema with SwiftData. For more information
- The schema is applied to the ModelContainer class. And instances of the classes are mapped to a ModelContext in your code.
Configure Persistence
- The model container is the bridge between the schema and where it is stored
- You can instantiate easily with try ModelContainer(for: SCHEMA.self) it will infer related types
- The ModelConfiguration class describes the persistence of the schema
- On disk or in memory
- File location (or generate one for you)
- Read Only mode
- And you can tell it which cloudKit container to use
- Note in the above example we define all the Schema’s will use, Where we want to store, including our cloudKit container for each Schema as appropriate (since we want to keep People separate from Trips data)
- Finally we would create the container with `let container = try ModelContainer(for: fullSchema, trips, people)`
- You can use modeContainer modifier to a view or scene to describe which ones you will use in that view or scene
Track and Persist changes
- The model and modelContext
- The the modelContainer modifier binds the @Environment to the modelContext
- Changes are stored as snapshots in the modelContext until you call context.save() – this will persist changes to modelContainer
- This modelContext works in coordination with the ModelContainer – which supports rollback and reset (for undo and autosave)
- The modelContainer has a isUndoEnabled: value. This means that system gestures like shake and three finger swipe will automatically do undo for you.
- Autosave will save during system events like moving to foreground or background. You can disable vis isAutosaveEnabled. It is enabled by default in applications, but it is disabled for modelContexts created by hand.
Modeling at scale
- Background operations, sync and batch processing all work with model objects
- Using Predicate Macro you can simplify queries and subqueries using Swift.
- You can add additional tuning parameters in the enumerate function on modelContext, this will be implicitly efficient. Using platform best practices, like batching (which you can modify if you desire). It will also implement mutation guards by default, you can override with allowEscapingMutations.