In SwiftUI, if multiple child views need to access a common property or method, the common approach is to pass down the reference of the class (where the common property or method is defined) from the root view to all its children through constructors. This can lead to code duplication and maintenance overhead.
However, there is a way to avoid passing references to every child view. In SwiftUI, we can use the @EnvironmentObject
property wrapper to create an object that can be shared across different views.
Here's how to do it:
main.swift96 chars4 lines
main.swift43 chars2 lines
AppData
, declare a @EnvironmentObject
property:main.swift40 chars2 lines
appData
property to access the shared data or functionality:main.swift136 chars8 lines
Now, you can access the appData
object from any child view without needing to pass it down the view hierarchy. Make sure that you only modify the appData
object from the root view or a view that has access to it.
gistlibby LogSnag