Bird
0
0

Consider this SwiftUI code snippet:

medium📝 Predict Output Q4 of 15
iOS Swift - State Management in SwiftUI
Consider this SwiftUI code snippet:
struct ParentView: View {
  @State private var score = 5
  var body: some View {
    VStack {
      Text("Score: \(score)")
      ScoreView(score: $score)
    }
  }
}

struct ScoreView: View {
  @Binding var score: Int
  var body: some View {
    Button("Add 3") {
      score += 3
    }
  }
}
What will be displayed in the Text after tapping the button once?
AScore: 8
BScore: 5
CScore: 3
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Initial state

    The parent view's score starts at 5.
  2. Step 2: Binding usage

    The child view receives a binding to score, so changes in the child update the parent's state.
  3. Step 3: Button action

    When the button is tapped, score += 3 increments the parent's score to 8.
  4. Step 4: UI update

    The Text reflects the updated score immediately.
  5. Final Answer:

    Score: 8 -> Option A
  6. Quick Check:

    Binding updates parent state [OK]
Quick Trick: Bindings sync child changes to parent state instantly [OK]
Common Mistakes:
  • Assuming child changes don't affect parent
  • Confusing value passing with binding
  • Ignoring state update propagation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes