Bird
0
0

Given this SwiftUI code, what will be displayed after pressing the button twice?

medium📝 Predict Output Q4 of 15
iOS Swift - State Management in SwiftUI
Given this SwiftUI code, what will be displayed after pressing the button twice?
struct ContentView: View {
  @State private var clicks = 0
  var body: some View {
    VStack {
      Text("Clicks: \(clicks)")
      Button("Tap") {
        clicks += 1
      }
    }
  }
}
AClicks: 0
BClicks: 1
CClicks: Tap
DClicks: 2
Step-by-Step Solution
Solution:
  1. Step 1: Understand @State variable behavior on button press

    Each button tap increments clicks by 1, updating the state and UI.
  2. Step 2: Calculate clicks after two taps

    Starting from 0, after two taps clicks = 2, so Text shows "Clicks: 2".
  3. Final Answer:

    The Text will display "Clicks: 2" after two button presses. -> Option D
  4. Quick Check:

    @State increments reflect in UI immediately [OK]
Quick Trick: Each button tap updates @State and refreshes UI [OK]
Common Mistakes:
  • Assuming clicks does not update
  • Confusing button label with state value
  • Ignoring state variable initialization

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes