
Swiftdata
- 215 installs
- 297 repo stars
- Updated August 4, 2026
- vabole/apple-skills
Model, persist, migrate, and query on-device data with SwiftData and SwiftUI in iOS apps needing local storage, sync prep, or offline-first catalogs.
About
Teaches Claude how to implement Apple SwiftData persistence in native apps: defining models, configuring containers, performing fetches and saves, handling migrations, and integrating with SwiftUI for offline-first mobile data layers.
- @Model schema and relationships
- ModelContainer and ModelContext setup
- Fetch descriptors, sorting, and predicates
- Migration and versioning strategies
- SwiftUI @Query integration patterns
Swiftdata by the numbers
- 215 all-time installs (skills.sh)
- +4 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #423 of 1,039 Mobile Development skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/vabole/apple-skills --skill swiftdataAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 215 |
|---|---|
| repo stars | ★ 297 |
| Last updated | August 4, 2026 |
| Repository | vabole/apple-skills ↗ |
What it does
Model, persist, migrate, and query on-device data with SwiftData and SwiftUI in iOS apps needing local storage, sync prep, or offline-first catalogs.
Files
SwiftData Documentation
Search these docs to answer questions about SwiftData APIs.
Return Format
Always include: 1. Summary - Answer the question concisely 2. File paths - List relevant files for full details, e.g.:
swiftdata-model.mdfor @Model macroswiftdata-query.mdfor @Query usage
Files
swiftdata-index.md- Framework overview and all available APIsswiftdata-model.md- @Model macro and model definitionswiftdata-modelcontext.md- ModelContext for CRUD operationsswiftdata-query.md- @Query property wrapper for fetching data
Navigation: SwiftData
Macro
Model()
Available on: iOS 17.0+, iPadOS 17.0+, Mac Catalyst 17.0+, macOS 14.0+, tvOS 17.0+, visionOS 1.0+, watchOS 10.0+, Swift 5.9+
Converts a Swift class into a stored model that’s managed by SwiftData.
@attached(member, conformances: Observable, PersistentModel, Sendable, names: named(_$backingData), named(persistentBackingData), named(schemaMetadata), named(init), named(_$observationRegistrar), named(_SwiftDataNoType), named(access), named(withMutation)) @attached(memberAttribute) @attached(extension, conformances: Observable, PersistentModel, Sendable) macro Model()Overview
Annotate your model classes with the @Model macro to make them persistable. At build time, the macro expands to provide conformance to the PersistentModel and Observable protocols.
@Model
class RemoteImage {
var sourceURL: URL
var data: Data
init(sourceURL: URL, data: Data = Data()) {
self.sourceURL = sourceURL
self.data = data
}
}For more information about defining models, see Preserving your app’s model data across launches.
Model definition
- Attribute(_:originalName:hashModifier:)) Specifies the custom behavior that SwiftData applies to the annotated property when managing the owning class.
- Unique(_:)) Specifies the key-paths that SwiftData uses to enforce the uniqueness of model instances.
- Index(_:)-74ia2) Specifies the key-paths that SwiftData uses to create one or more binary indices for the associated model.
- Index(_:)-7d4z0) Specifies the key-paths that SwiftData uses to create one or more indicies for the associated model, where each index is either binary or R-tree.
- Defining data relationships with enumerations and model classes Create relationships for static and dynamic data stored in your app.
- Relationship(_:deleteRule:minimumModelCount:maximumModelCount:originalName:inverse:hashModifier:)) Specifies the options that SwiftData needs to manage the annotated property as a relationship between two models.
- Transient()) Tells SwiftData not to persist the annotated property when managing the owning class.
---
Extracted from Apple DocC JSON by apple-skills tooling. This is unofficial content. All documentation belongs to Apple Inc.
Navigation: SwiftData
Class
ModelContext
Available on: iOS 17.0+, iPadOS 17.0+, Mac Catalyst 17.0+, macOS 14.0+, tvOS 17.0+, visionOS 1.0+, watchOS 10.0+, Swift 5.9+
An object that enables you to fetch, insert, and delete models, and save any changes to disk.
class ModelContextOverview
A model context is central to SwiftData as it’s responsible for managing the entire lifecycle of your persistent models. You use a context to insert new models, track and persist changes to those models, and to delete those models when you no longer need them. A context understands your app’s schema but doesn’t know about any individual models until you tell it to fetch some from the persistent storage or populate it with new models. Afterwards, any changes made to those models exist only in memory until the context implicitly writes them to the persistent storage, or you manually invoke save()). For more information about implicit writes, see autosaveEnabled.
If your app’s schema describes relationships between models, you don’t need to manually insert each model into the context when you first create them. Instead, create the graph of related models and insert only the graph’s root model into the context. The context recognizes the hierarchy and automatically handles the insertion of the related models. The same behavior applies even if the graph contains both new and existing models.
A model context depends on a model container for knowledge about your app’s schema and persistent storage. After you attach a container to your app’s window group or view hierarchy, an associated context becomes available in the SwiftUI environment. This context is bound to the main actor and the framework configures the context to implicitly save future model changes. The Query()) macros use the same context to perform their fetches.
struct LastModifiedView: View {
@Environment(\.modelContext) private var modelContext
}Important: If you don’t explicitly attach a model container, the environment provides a context bound to an in-memory, schema-less container. Any attempt to insert a model into this context causes the framework to throw an error, and any fetches you run will return empty results.
After you establish access to a model context, use that context’s insert(_:)) and delete(_:)) methods to add and remove models. You can also delete several models at once using delete(model:where:includeSubclasses:)). There isn’t a corresponding method to update a model because the context automatically tracks all changes to its known models. Use the hasChanges property to determine if the context has unsaved changes, and call rollback()) to discard any pending inserts and deletes and any restore changed models to their most recent saved state.
Although you fetch models primarily with the Query() macro (and its variants), you can use a model context to perform almost identical fetches. For example, use the fetch(_:)) and fetch(_:batchSize:)) methods to retrieve all models of a certain type that match a set of criteria. And use fetchCount(_:)) to determine the number of models that match some criteria without the overhead of fetching the models themselves. If you need to be able to identify models that match some criteria but don’t require all of the associated data, use fetchIdentifiers(_:)) and fetchIdentifiers(_:batchSize:)) to retrieve only those models’ persistent identifiers.
A model context posts a willSave notification before it attempts a save operation, and a didSave notification immediately after that operation succeeds. Subscribe to one, or both, of these notifications if your app needs to be aware of these events. The didSave notification provides additional information about any inserted, updated, and deleted models.
struct LastModifiedView: View {
@Environment(\.modelContext) private var context
@State private var lastModified = Date.now
private var didSavePublisher: NotificationCenter.Publisher {
NotificationCenter.default
.publisher(for: ModelContext.willSave, object: context)
}
var body: some View {
Text(lastModified.formatted(date: .abbreviated, time: .shortened))
.onReceive(didSavePublisher) { _ in
lastModified = Date.now
}
}
}Note: To avoid receiving unwanted or unexpected notifications, always specify the model context as the object parameter when creating a publisher.Conforms To
Creating a model context
- init(_:)) Creates a context that belongs to the specified model container.
- ModelContainer An object that manages an app’s schema and model storage configuration.
Fetching models
- fetch(_:)) Returns an array of typed models that match the criteria of the specified fetch descriptor.
- fetch(_:batchSize:)) Returns a collection of typed models, in batches, which match the criteria of the specified fetch descriptor.
- fetchCount(_:)) Returns the number of models that match the criteria of the specified fetch descriptor.
- FetchDescriptor A type that describes the criteria, sort order, and any additional configuration to use when performing a fetch.
- FetchResultsCollection A collection that efficiently provides the results of a completed fetch.
- enumerate(_:batchSize:allowEscapingMutations:block:)) Runs a closure for each model that matches the criteria of the specified fetch descriptor.
- model(for:)) Returns the persistent model for the specified identifier.
- registeredModel(for:)) Returns the typed model for the specified identifier.
Inserting models
- insertedModelsArray The array of inserted models that the context is yet to persist.
- insert(_:)) Registers the specified model with the context so it can include the model in the next save operation.
Modifying models
- hasChanges A Boolean value that indicates whether the context has unsaved changes.
- changedModelsArray The array of registered models that have unsaved changes.
Deleting models
- deletedModelsArray The array of registered models that the context will remove from the persistent storage during the next save operation.
- delete(_:)) Removes the specified model from the persistent storage during the next save operation.
- delete(model:where:includeSubclasses:)) Removes each model satisfying the given predicate from the persistent storage during the next save operation.
Persisting unsaved changes
- autosaveEnabled A Boolean value that indicates whether the context should automatically save any pending changes when certain events occur.
- save()) Writes any pending inserts, changes, and deletes to the persistent storage.
- transaction(block:)) Runs the provided closure, and once it finishes, writes any pending inserts, changes, and deletes to the persistent storage.
- rollback()) Discards pending inserts and deletes, restores changed models to their most recent committed state, and empties the undo stack.
Fetching only persistent identifiers
- fetchIdentifiers(_:)) Returns an array of persistent identifiers, where each identifier represents a single model that satisfies the criteria of the specified fetch descriptor.
- fetchIdentifiers(_:batchSize:)) Returns a collection of persistent identifiers, in batches, where each identifier represents a single model that satisfies the criteria of the specified fetch descriptor.
Accessing the container
- container The context’s model container.
Performing undo and redo
- processPendingChanges()) Tells the undo manager to record any changes made to the context’s registered models.
- undoManager The object that provides undo support for the context.
Registering for notifications
- willSave A notification that posts when the context is about to process pending inserts, changes, and deletes.
- didSave A notification that posts when the context finishes processing pending inserts, changes, and deletes.
- ModelContext.NotificationKey Describes the data in the user info dictionary of a notification sent by a model context.
Debugging contexts
- debugDescription A textual representation of the context, suitable for debugging.
Instance Properties
Instance Methods
Model life cycle
- ModelContainer An object that manages an app’s schema and model storage configuration.
- Fetching and filtering time-based model changes Track all inserts, updates, and deletes that occur in a data store and process them as a series of chronological transactions.
- HistoryDescriptor A type that describes the criteria, and, optionally, sort order, to use when fetching history data
- Deleting persistent data from your app Explore different ways to use SwiftData to delete persistent data.
- Reverting data changes using the undo manager Automatically record data change operations that people perform in your SwiftUI app, and let them undo and redo those changes.
- Syncing model data across a person’s devices Add the required capabilities and define a compatible schema to enable SwiftData to automatically sync your app’s model data using iCloud.
- Concurrency support Types you use to access model attributes and perform storage-related tasks in a safe and isolated way.
---
Extracted from Apple DocC JSON by apple-skills tooling. This is unofficial content. All documentation belongs to Apple Inc.
Navigation: SwiftData
Structure
Query
Available on: iOS 17.0+, iPadOS 17.0+, Mac Catalyst 17.0+, macOS 14.0+, tvOS 17.0+, visionOS 1.0+, watchOS 10.0+
A type that fetches models using the specified criteria, and manages those models so they remain in sync with the underlying data.
@MainActor @preconcurrency struct Query<Element, Result> where Element : PersistentModelConforms To
Creating a query
- init(_:animation:)) Create a query with a SwiftData fetch descriptor.
- init(filter:sort:animation:)) Create a query with a predicate, and a list of sort descriptors.
- init(filter:sort:order:animation:)-1qfoj) Creates a query with a predicate, a key path to a property for sorting, and the order to sort by.
- init(filter:sort:order:animation:)-3qovd) Creates a query with a predicate, a key path to a property for sorting, and the order to sort by.
- init(_:transaction:)) Create a query with a SwiftData fetch descriptor.
- init(filter:sort:transaction:)) Create a query with a predicate, and a list of sort descriptors.
- init(filter:sort:order:transaction:)-2bx9a) Create a query with a predicate, a key path to a property for sorting, and the order to sort by.
- init(filter:sort:order:transaction:)-8q7vs) Create a query with a predicate, a key path to a property for sorting, and the order to sort by.
Getting query configuration
- modelContext Current model context
Queryinteracts with. - fetchError An error encountered during the most recent attempt to fetch data.
Accessing the value
- wrappedValue The most recent fetched result from the Query.
Model fetch
- Filtering and sorting persistent data Manage data store presentation using predicates and dynamic queries.
- Query()) Fetches all instances of the attached model type.
- Additional query macros Supplementary macros that enable you to narrow query results and tell SwiftData how to sort and order those results.
- FetchDescriptor A type that describes the criteria, sort order, and any additional configuration to use when performing a fetch.
---
Extracted from Apple DocC JSON by apple-skills tooling. This is unofficial content. All documentation belongs to Apple Inc.