1

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?

Damian Dudycz
  • 2,622
  • 19
  • 38

1 Answers1

2

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:

pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • What would happend if I define two variables of the same Type? Will they just both be assigned to the last one provided? – Damian Dudycz Jun 29 '20 at 19:10
  • @DamianDudycz Please see [Why can't swiftui distinguish 2 different environment objects?](https://stackoverflow.com/questions/61804474/why-cant-swiftui-distinguish-2-different-environment-objects) and [How to set multiple EnvironmentObjects which are same type](https://stackoverflow.com/questions/57360838/how-to-set-multiple-environmentobjects-which-are-same-type/57366566#57366566) – pawello2222 Jun 29 '20 at 19:12