Bird
0
0

How do you correctly supply an @EnvironmentObject to a SwiftUI view so that it can access shared data?

easy📝 Conceptual Q2 of 15
iOS Swift - State Management in SwiftUI
How do you correctly supply an @EnvironmentObject to a SwiftUI view so that it can access shared data?
AUse <code>@ObservedObject</code> in the parent view and <code>@State</code> in the child view
BDeclare the object inside the child view using <code>@StateObject</code>
CPass the object as a parameter to the child view's initializer
DAttach the object to a parent view using <code>.environmentObject(_:) </code> modifier
Step-by-Step Solution
Solution:
  1. Step 1: Understand environment injection

    The environmentObject modifier attaches an observable object to the environment for all child views.
  2. Step 2: Differentiate from other property wrappers

    @StateObject creates and owns an object; @ObservedObject observes but does not inject into environment.
  3. Final Answer:

    Attach the object to a parent view using .environmentObject(_:) modifier -> Option D
  4. Quick Check:

    Use .environmentObject to provide shared data [OK]
Quick Trick: Use .environmentObject modifier on parent view [OK]
Common Mistakes:
  • Trying to create @EnvironmentObject inside child view
  • Passing environment objects via initializers instead of environment
  • Confusing @ObservedObject with environment injection

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes