-
The ProblemI'm finding that SwiftUI views don't properly propagate dependencies to nested views. I created a demo in this gist (Drop it into a project that's got access to swift-dependencies) To break it down more simply, if I have a structure like this: struct InnerView: View {
@Dependency(\.text) var text
var body: some View {
Text(text)
}
}
struct OuterView: View {
@Dependency(\.text) var text
var body: some View {
Text(text)
InnerView()
}
} And I want to preview my struct OuterView_Previews: PreviewProvider {
static var previews: some View {
withDependencies {
$0.text = "Injected - withDependencies"
} operation: {
OuterView()
}
}
}
My Current Workaroundswift-dependencies doesn't seem to propagate among views, but of course, A Hiccup with the WorkaroundIf I was really hoping for |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @dafurman, the withDependencies {
$0.text = "Injected - withDependencies"
} operation: {
OuterView()
} …you are only executing the initializer of We were able to solve this problem for model objects using In the end, |
Beta Was this translation helpful? Give feedback.
Hi @dafurman, the
@Dependency
property wrapper is not meant to be used in views if you need to be able to scope/propagate dependency changes. It is not even possible to have dependencies propagate to views without SwiftUI opening up more of its internals. By doing this:…you are only executing the initializer of
OuterView
with the dependencies altered, not thebody
of the view. If you use@Dependency
in a view then the only benefits you get really are the live/preview/test value, but you do not get the ability to dynamically change the dependencies.We were able to solve this problem for model obj…