Reputation: 2800
Lets say I have a View
with Environment Object
like this:
struct MyView: View {
@EnvironmentObject
var viewModel: RegisterViewModel
}
and somewhere in ancestor I would provide this object like this:
NavigationView {
LoginView()
}
.environmentObject(RegisterViewModel())
What is the mechanics of actually assigning this value to var viewModel
. Nowhere in my code I needed to specify the name of variable, and yet it's correctly assigned. What will happened if I have few environment objects of the same type?
Upvotes: 1
Views: 686
Reputation: 54516
EnvironmentObjects are identified by type.
SwiftUI just looks for environment variables for a specific type (here it's RegisterViewModel
) and uses the first one it finds.
This code puts RegisterViewModel
to the environment:
.environmentObject(RegisterViewModel())
Then, when building a View, SwiftUI looks for a RegisterViewModel
type in the environment:
@EnvironmentObject var viewModel: RegisterViewModel
More details:
Upvotes: 2