In SwiftUI, when a child view receive a binding to a state in its parent view, it can pass it further to its own child view by using that binding's projected value, because a binding's projected value is also a binding.
But we can't use a similar approach to pass down a
ObservedObject in view hierarchy, because 1)
ObservedObject's projected value is not of
ObservedObject type, and 2)
ObservedObject doesn't have a
init() which takes an argument of
ObservedObject type. It seems that SwiftUI developers intentionally don't support this approach, Instead they introduced
EnvironmentObject for this purpose.
My question is about another (naive) approach: what if the a child view passes the
ObservableObject (the one it receives from its parent view) to its child view's
init()? I guess the approach must have issues, otherwise SwiftUI developers wouldn't introduce
EnvironmentObject. But what are the issues? I found a discussion on SO, in which the accepted answer has the following:
Finally, regarding why your solution is not working, you must consider a single source of truth (the observable object in your Parent) ...
I doubt about the explanation. Unlike state value,
ObservableObject is a reference, so I don't think passing it down in view hierarchy violates the single source of truth principle, does it? That said, I don't see people doing it. So is it a rule in SwiftUI design?
While it's probably only SwiftUI developers that really know the reason behind the design choice, I wonder if anyone knows if the approach I described above has a fundamental issue , or it's just that it has subtle issues and the introduction of
EnvironmentObject solves them? Thanks for any opinions.