How to get a SwiftData model container and context in SwiftUI
Learn how to setup a SwiftData container and context directly in SwiftUI.
30 Oct 2023 · 4 min read
At WWDC23, Apple introduced SwiftData - a framework which focuses on persisting data by using declarative code. In this overview on SwiftData for iOS, we already looked at the basics of SwiftData.
In this article, we'll look at view modifiers which we can use to setup a SwiftData container and context directly in SwiftUI.
Let's get started.

In the previous article, we already learned on how to setup a SwiftData model container:
let modelContainer = try ModelContainer(for: [User.self])
When working with SwiftUI, we can alternatively use the modelContainer view modifier as follows:
struct ExampleApp: App {var body: some Scene {WindowGroup {ContentView()}.modelContainer(for: [User.self])}}
The example above creates a container for the whole window groupe scene. The window and its views will inherit the container.
If a view needs its own container, we can setup one in the same way by applying the modelContainer modifier to a specific view. Changes to one container won't affect another container.
When we setup the model container through the view modifier as shown above, it makes the model context available through the application's environment:
@Environment(\.modelContext) private var context
We can use the environment to get the model context in any SwiftUI view we need.

Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips