How to modify dependencies of child views in SwiftUI previews? #74
-
Hello! I was wondering how a dependency can be modified in a SwiftUI preview so that the view and all of its child views use the modified dependency. I ran into the issue that when modifying the dependency with the See this minimal example: enum ExampleKey: DependencyKey {
static let testValue = "testValue"
static let previewValue = "previewValue"
static let liveValue = "liveValue"
}
extension DependencyValues {
var exampleDependency: String {
get { self[ExampleKey.self] }
set { self[ExampleKey.self] = newValue }
}
}
struct ParentView: View {
var body: some View {
ChildView()
}
}
struct ChildView: View {
@Dependency(\.exampleDependency) private var exampleDependency
var body: some View {
Text(exampleDependency)
}
}
struct ParentView_Previews: PreviewProvider {
static var previews: some View {
withDependencies {
$0.exampleDependency = "new value"
} operation: {
ParentView()
}
}
} The preview does show the general "previewValue" text instead of the modified "new value" text. It works when injecting the child view into the parent view, but this doesn't seem to be a practical option in general. So I am wondering how to achieve this when using dependencies in child views? Or are they not intended to be used like this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hey @chwo! |
Beta Was this translation helpful? Give feedback.
-
Hi @chwo, we don't think In order to get dependencies properly propagating through vanilla SwiftUI features, you need to use |
Beta Was this translation helpful? Give feedback.
Hey @chwo!
@Dependency
is not meant to be used inView
, because we don't control the view's creation process, and we're not able to correctly propagate dependencies across the view tree.One thing you can do however is to create an
ObservedObject
that hosts@Dependency
properties, and share this model either directly, or usingEnvironmentObject
. Please note that if you store this model instance usingStateObject
, you may need a little more work to make sure that the dependencies are correctly captured. I'm explaining the problem and providing a workaround here.It is otherwise fine to define dependencies overrides in previews, provided they're captured by the model and not by the view. I …