Introduction
Property wrappers are so important in SwiftUI as they modify the state of our application. SwiftUI is an imperative programming language that means that we have to tell the app what we want exactly instead of declaring them all. Because of the paradigm of this language, we need some modifiers that make us able to modify the state of our app whenever we want, what is the reason of the existence of the property wrappers, they permit us to modify the state of our app. We have so many property wrappers but today we are going to talk about the @EnvironmentObject, which is a little bit difficult to understand but so so good to use in our apps and projects.
Disclaimer: How we continue I have to tell you how we are going to work in this article, we will have three views, a main view, a View2 and a View3 and we will send that information to all the views using the @EnvironmentObject property wrapper
Why @EnvironmentObject?
First of all, the number one question, why we do have to use @EnvironmentObject? Well, there are some reasons of why we use it, first of all, we have to understand how we pass information between views in SwiftUI. We have three main property wrappers that help us passing information between views, @StateObject, @ObservedObject and @EnvironmentObject, @StateObject make us able to send information to just one view, when we try to pass that info into more than one view we can run into some troubles. That's what @ObservedObject tries to fix, it send information to more views but we have to pass the information to the View2 before it can get into View3 that's the reason of existence of @EnvironmentObject, it send that information into a higher zone which is the environment of the app and makes us able to send that into every single view that we want, see it as the cloud, when we upload something to the cloud we can access to it from any device this is the same, decorating a value with @EnvironmentObject sends that value to the "cloud" (Environment) and makes us able to share it to any other view in the project so View3 will have access to the @EnvironmentObject without passing it through the View2.
Let's start working!
So, we will locate in our main view and we will create a variable which in this case will point to a view model and we have to mark it as @StateObject. Now, in the view of the same view we have to place the modifier .environmentObject() and inside the parenthesis indicate the variable that we have just created.
This is how it should look.
At this point, our viewModel is already in the environment now we can go to the View3 and add an environment object that points to the view model.
And that's pretty much it! Now you will have access to your view model from anywhere!
I hope you've enjoyed it and learnt a little bit about SwiftUI and how this wonderful and powerful property wrapper works which is my absolute favourite as it makes sending information between views so so easy!
Top comments (0)