44

In SwiftUI it is possible to use the environmentObject method of the View object to put a single BindableObject into the environment.

What if I want to put multiple BindableObjects at the same time into the environment? I don't see any solution for this in the SwiftUI documentation. I don't want to have to pass the objects in the constructor.

Kaushik Makwana
  • 1,329
  • 2
  • 14
  • 24
ideveloper
  • 473
  • 1
  • 4
  • 10

1 Answers1

105

The call to environmentObject() returns a (modified) view, therefore you can chain the calls to put multiple objects into the environment. Example:

 let rootView = ContentView()
     .environmentObject(firstBindable)
     .environmentObject(secondBindable)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 2
    How are the objects referenced? Is there supporting docs to learn more? – Michael Ozeryansky Oct 09 '19 at 05:25
  • @MichaelOzeryansky: I don't know how it is implemented. I watched the WWDC video about SwiftUI, and figured out the rest by try and error. – Martin R Oct 13 '19 at 07:49
  • 10
    Based off of compiler errors, it seems it looks for an object matching the same type. And it also uses the first `environmentObject` attached when there are multiple of the same type. – Michael Ozeryansky Oct 13 '19 at 19:44
  • Probably using the type name as the key. This is a valid use case when there are multiple views of the same type. For example, calculating the light value difference between two camera exposures (very common for photographers, I'm speaking from experience). https://www.scantips.com/lights/exposurecalc.html – Abhijit Sarkar Jul 13 '20 at 11:35
  • 3
    I wish I could click the up arrow 50 times! This was KILLING me. Thank you! – Scooter Sep 26 '20 at 01:03