Most of the examples Apple provides to demonstrate Dependency Injection in SwiftUI use @Environment
. When creating a new project with SwiftData
in XCode, you’ll notice that the template uses Environment
for injecting the modelContext
.
Swift
struct ContentView: View {
@Environment(\.modelContext) private var modelContext // <-- 1
@Query private var items: [Item]
var body: some View {
NavigationSplitView {
List {
...
}
.toolbar {
ToolbarItem {
Button(action: addItem) {
...
}
}
}
}
...
}
private func addItem() {
withAnimation {
let newItem = Item(timestamp: Date())
modelContext.insert(newItem) // <-- 2
}
}
...
}
#Preview {
ContentView()
.modelContainer(for: Item.self, inMemory: true) // <-- 3
}
This article has been indexed from DZone Security Zone