Could you please provide some guidance/documentation for how to use swift-dependencies along with SwiftData? #361
Replies: 2 comments 1 reply
-
Dependency values must be I'm not super familiar with SwiftData, but it does provide a |
Beta Was this translation helpful? Give feedback.
-
Thought I'd provide a bit more context and some updates after spending a few hours on this today. Initially, I had set up I was able to get around the issues by adding a Therefore, I looked into Dependency Injection frameworks, and swift-dependencies seemed like a simple one. However, at this point, I ran into the problem of the ModelContext not being Sendable. I also tried using https://github.com/hmlongco/Factory and ran into the same issue. In the end, I ended up not using a Dependency Injection library and instead instantiating the objects in MyApp.swift directly, and passing them along to any descendant classes via SwiftUI's environment as described here. Whilst this works, I think in the long run, I could end up having to create a lot of objects in MyApp.swift and passing them all along via SwiftUI's environment. This isn't ideal because every time any of the values in the object changes, the view’s body will be re-evaluated, even if the value changed is not a value that is used by this specific view (as described in this article). I can see from the swift-dependencies docs docs that it's possible to specify a minimal interface as the dependency for a view. Perhaps there are other reasons not to use the environment too, and prefer a dependency injection framework. I'd be interested to learn what they are. I just need to figure out the right pattern to use it with something that's not Sendable. |
Beta Was this translation helpful? Give feedback.
-
Description
Can swift-dependencies be used along with SwiftData?
Specifically, if I have classes that depend on ModelContext bound to the main actor, then how can I initialise those dependencies?
Example:
I ran into error:
I'm relatively new to Swift and SwiftData - so do let me know if I'm going about this the wrong way or shouldn't be using swift-dependencies here.
Checklist
main
branch of this package.Expected behavior
No response
Actual behavior
No response
Steps to reproduce
No response
Dependencies version information
No response
Destination operating system
No response
Xcode version information
Version 16.3
Swift Compiler version information
Beta Was this translation helpful? Give feedback.
All reactions