Hello all!
I'm still fairly new to SwiftData, but have recently integrated it into one of my apps which has been going great.
Currently, I have this integrated into my project like so (code simplified for illustration):
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: Todo.self)
}
}
struct ContentView: View {
@Query(sort: \Todo.date) var todos: [Todo]
@Environment(\.modelContext) var moc
var body: some View {
...
}
}
In my app, the ContentView struct then also contains business logic in the form of various methods to create and modify entities stored in SwiftData.
In order to achieve better separation of concerns and make SwiftTesting the view easier, I'd love to move all this business logic code out into a view model.
Unfortunately, I understand that this causes issues due to view models not having access to the SwiftUI environment, making it difficult to inject the model container into a view model and using that model to initialize queries.
There are some approaches to this that I found which end up defining another layer on top of SwiftData, but I can see how doing that may result in state syncronization issues between what is stored in SwiftData and the model accessing it.
Given that MVVM is so popular and widely used, is there a recommended approach of doing this in a consistent way while still preserving state safety between the SwiftData model and the view model?
Thanks for any suggestions!
Cheers,
Robin
Topic:
App & System Services
SubTopic:
SwiftData