Bird
0
0

Given the code below, what will be displayed when ContentView is shown?

medium📝 Predict Output Q13 of 15
iOS Swift - State Management in SwiftUI
Given the code below, what will be displayed when ContentView is shown?
class Counter: ObservableObject {
  @Published var count = 0
}

struct ContentView: View {
  @EnvironmentObject var counter: Counter
  var body: some View {
    Text("Count: \(counter.count)")
  }
}

// In the app entry point:
// ContentView().environmentObject(Counter())
ARuntime error due to missing environment object
BCount: 0
CCount: nil
DCount: 1
Step-by-Step Solution
Solution:
  1. Step 1: Understand initial state of Counter

    The Counter class starts with count = 0, and this is published to views.
  2. Step 2: Check environment object injection

    The app injects Counter() into ContentView with .environmentObject(Counter()), so the view can access count.
  3. Final Answer:

    Count: 0 -> Option B
  4. Quick Check:

    Initial count is 0 and environment object is provided = D [OK]
Quick Trick: Initial @Published values show as is when environment object is injected [OK]
Common Mistakes:
  • Assuming count starts at 1
  • Thinking environment object is missing
  • Confusing with optional values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes