Bird
0
0

What is wrong with this code snippet?

medium📝 Debug Q7 of 15
iOS Swift - State Management in SwiftUI
What is wrong with this code snippet?
struct ContentView: View {
  @EnvironmentObject var settings: Settings
  var body: some View {
    VStack {
      Text(settings.username)
    }
  }
}

// Usage
ContentView().environmentObject(Settings())
ASettings must be a class conforming to ObservableObject.
BThe @EnvironmentObject property wrapper requires initialization.
CText cannot display a String directly.
DenvironmentObject() modifier should be applied to ContentView's parent, not ContentView itself.
Step-by-Step Solution
Solution:
  1. Step 1: Check environmentObject injection location

    The .environmentObject() modifier should be applied on a parent view, not directly on ContentView instance.
  2. Step 2: Verify other options

    Settings must be ObservableObject (assumed correct), Text can display String, and @EnvironmentObject does not require initialization.
  3. Final Answer:

    environmentObject() modifier should be applied to ContentView's parent, not ContentView itself. -> Option D
  4. Quick Check:

    Inject environment object on parent view [OK]
Quick Trick: Apply .environmentObject() on parent views, not on the view itself [OK]
Common Mistakes:
  • Applying .environmentObject() on the view instance directly
  • Confusing ObservableObject conformance
  • Misunderstanding Text view capabilities

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes