Bird
0
0

Consider this SwiftUI code snippet:

medium📝 Predict Output Q13 of 15
iOS Swift - State Management in SwiftUI
Consider this SwiftUI code snippet:
struct ContentView: View {
  @State private var count = 0
  var body: some View {
    VStack {
      Text("Count: \(count)")
      Button("Add") {
        count += 1
      }
    }
  }
}
What happens when the "Add" button is tapped?
AThe app crashes because count is private
BThe count increases but the Text does not update
CThe count increases by 1 and the Text updates to show the new count
DNothing happens because @State variables cannot change
Step-by-Step Solution
Solution:
  1. Step 1: Understand @State behavior on change

    When the button increments count, the @State variable changes.
  2. Step 2: UI updates automatically

    SwiftUI detects the change and refreshes the Text to show the new count value.
  3. Final Answer:

    The count increases by 1 and the Text updates to show the new count -> Option C
  4. Quick Check:

    @State change triggers UI update = C [OK]
Quick Trick: @State changes always refresh the UI automatically [OK]
Common Mistakes:
  • Thinking private stops UI updates
  • Assuming UI won't refresh on state change
  • Believing @State variables are immutable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes