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:

  1. 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.

  2. 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.

  3. 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).