Bird
0
0

Given the code below, what will be printed when the button is tapped?

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

struct ContentView: View {
  @StateObject var counter = Counter()

  var body: some View {
    VStack {
      Text("Count: \(counter.count)")
      Button("Increment") {
        counter.count += 1
        print(counter.count)
      }
    }
  }
}
ACount: 0 initially, then prints 0 on button tap
BCount: 0 initially, then prints 1 on button tap
CCount: 1 initially, then prints 2 on button tap
DCompilation error due to missing @ObservedObject
Step-by-Step Solution
Solution:
  1. Step 1: Understand initial state and updates

    The counter starts at 0. The Text shows "Count: 0" initially.
  2. Step 2: Analyze button action

    When tapped, counter.count increments by 1, so it becomes 1, and prints 1.
  3. Final Answer:

    Count: 0 initially, then prints 1 on button tap -> Option B
  4. Quick Check:

    Initial 0, increment prints 1 [OK]
Quick Trick: Remember: @StateObject updates view and prints new value [OK]
Common Mistakes:
  • Assuming count starts at 1 instead of 0
  • Thinking print shows old value before increment
  • Confusing @StateObject with @ObservedObject usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes