SwiftData
Write your model code declaratively to add managed persistence and efficient model fetching.
Overview
Combining Core Data’s proven persistence technology and Swift’s modern concurrency features, SwiftData enables you to add persistence to your app quickly, with minimal code and no external dependencies. Using modern language features like macros, SwiftData enables you to write code that is fast, efficient, and safe, enabling you to describe the entire model layer (or object graph) for your app. The framework handles storing the underlying model data, and optionally, syncing that data across multiple devices.
SwiftData has uses beyond persisting locally created content. For example, an app that fetches data from a remote web service might use SwiftData to implement a lightweight caching mechanism and provide limited offline functionality.
[Image]
SwiftData is unintrusive by design and supplements your app’s existing model classes. Attach the Model() macro to any model class to make it persistable. Customize the behavior of that model’s properties with the Attribute(_:originalName:hashModifier:) and Relationship(_:deleteRule:minimumModelCount:maximumModelCount:originalName:inverse:hashModifier:) macros. Use the ModelContext class to insert, update, and delete instances of that model, and to write unsaved changes to disk.
To display models in a SwiftUI view, use the Query() macro and specify a predicate or fetch descriptor. SwiftData performs the fetch when the view appears, and tells SwiftUI about any subsequent changes to the fetched models so the view can update accordingly. You can access the model context in any SwiftUI view using the modelContext environment value, and specify a particular model container or context for a view with the modelContainer(_:) and modelContext(_:) view modifiers.
Topics
Essentials
Preserving your app’s model data across launchesAdding and editing persistent data in your appAdopting SwiftData for a Core Data appSwiftData updatesAdopting inheritance in SwiftData
Model definition
Model()Attribute(_:originalName:hashModifier:)Unique(_:)Index(_:)Index(_:)Defining data relationships with enumerations and model classesRelationship(_:deleteRule:minimumModelCount:maximumModelCount:originalName:inverse:hashModifier:)Transient()
Model life cycle
ModelContainerModelContextFetching and filtering time-based model changesHistoryDescriptorDeleting persistent data from your appReverting data changes using the undo managerSyncing model data across a person’s devicesConcurrency support
Model fetch
Model storage
Maintaining a local copy of server dataDefaultStoreDataStoreDataStoreBatchingHistoryProvidingBuilding a document-based app using SwiftDataModelDocument
History life cycle
HistoryChangeHistoryDeleteHistoryInsertHistoryTokenHistoryTransactionHistoryUpdateHistoryTombstoneDefaultHistoryInsertDefaultHistoryUpdateDefaultHistoryDeleteDefaultHistoryTokenDefaultHistoryTransaction