EnvironmentObject usage in SwiftUI
What is EnvironmentObject in SwiftUI?
We use State and Binding in SwiftUI when sharing data between navigation views. But let’s say we have more views and data that we get on the first screen and we want to use it a few views later in the navigation. We can create an initializer for each view, but it’s a tedious road. In this case, we have EnvironmentObject
to help us.
EnvironmentObject
is living all child navigation of this view that we can get it whenever we want. Let’s say we have ViewA
and ViewC
views and we get a ViewAInformation
object in the ViewA
view and want to use it in the ViewC
view.
We created ViewAInformation
a model and added it to ViewA
. Now we add .environmentObject(viewAModel)
to navigationView, in now viewAModel
is available in this environment. For use it add the following code to ViewC
.
Okay, done, run the app we’ll see like this:
Conclusion
Okay, we used @EnvironmentObject
to share variable in our view environment without passing to each view. Thanks for reading :)