48

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.

1 Answer 1

111

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)
Sign up to request clarification or add additional context in comments.

5 Comments

How are the objects referenced? Is there supporting docs to learn more?
@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.
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.
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). scantips.com/lights/exposurecalc.html
I wish I could click the up arrow 50 times! This was KILLING me. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.