How do you create a model context from SwiftData?
Asked on 06/14/2025
1 search
To create a model context from SwiftData, you need to understand the role of the model context and how it interacts with the data store. The model context is responsible for reading and writing data using a store in a model container. Here's a brief overview of the process:
-
Model Context and Store Interaction: The model context communicates with the store using requests and responses defined by the datastore protocol. For example, when fetching data, the model context sends a fetch request to the store, which retrieves the data and returns it as snapshots. The model context then creates persistent models from these snapshots for use in views or other operations.
-
Persistent Identifiers: Each model in the context is identified by a persistent identifier. When changes are made, such as adding or deleting models, the model context tracks these changes and updates the store accordingly. For instance, if a new model is inserted, it is initially given a temporary identifier, which is later replaced with a permanent one upon saving.
-
Custom Data Stores: You can create custom data stores by implementing the datastore protocol, which allows you to define how data is fetched and saved. This involves setting up configurations and snapshots to communicate model values with the model context.
For a detailed example of creating a custom data store with SwiftData, you can refer to the session Create a custom data store with SwiftData (04:50).

Create a custom data store with SwiftData
Combine the power of SwiftData’s expressive, declarative modeling API with your own persistence backend. Learn how to build a custom data store and explore how to progressively add persistence features in your app. To get the most out of this session, watch “Meet SwiftData” and “Model your schema with SwiftData” from WWDC23.

What’s new in SwiftData
SwiftData makes it easy to add persistence to your app with its expressive, declarative API. Learn about refinements to SwiftData, including compound uniqueness constraints, faster queries with #Index, queries in Xcode previews, and rich predicate expressions. Join us to explore how you can use all of these features to express richer models and improve performance in your app. To discover how to build a custom data store or use the history API in SwiftData, watch “Create a custom data store with SwiftData” and “Track model changes with SwiftData history”.

Platforms State of the Union
Discover the newest advancements on Apple platforms.