Bird
0
0

Given this code snippet, what will be printed when the button is tapped once?

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

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

  var body: some View {
    Button("Tap") {
      counter.count += 1
      print(counter.count)
    }
  }
}
A1
BButton tapped
C0
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand initial value and increment

    The count starts at 0 and increments by 1 when the button is tapped.
  2. Step 2: Check print output after increment

    After increment, count is 1, so print outputs 1.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    Increment then print = 1 [OK]
Quick Trick: Increment before print means output is 1 [OK]
Common Mistakes:
  • Printing before increment
  • Confusing initial value with updated value
  • Assuming compilation error due to ObservableObject

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes