Bird
0
0

You want a child view to toggle a Boolean value in the parent and also perform a side effect when toggled. Which approach correctly uses @Binding and triggers the side effect in the parent?

hard📝 Application Q15 of 15
iOS Swift - State Management in SwiftUI
You want a child view to toggle a Boolean value in the parent and also perform a side effect when toggled. Which approach correctly uses @Binding and triggers the side effect in the parent?
struct ParentView: View {
  @State private var isOn = false

  var body: some View {
    ChildView(isOn: $isOn)
      .onChange(of: isOn) { newValue in
        print("Toggled to \(newValue)")
      }
  }
}

struct ChildView: View {
  @Binding var isOn: Bool

  var body: some View {
    Toggle("Switch", isOn: $isOn)
  }
}
AThis code correctly uses @Binding and triggers side effect on toggle
BSide effect won't trigger because onChange must be inside ChildView
CToggle should not use $isOn, just isOn without $
DParent must pass isOn without $ to ChildView
Step-by-Step Solution
Solution:
  1. Step 1: Verify @Binding usage

    Parent passes binding with $isOn, ChildView uses @Binding and Toggle binds to $isOn correctly.
  2. Step 2: Check side effect trigger

    Parent uses .onChange(of: isOn) to run code when isOn changes, which works as expected.
  3. Final Answer:

    This code correctly uses @Binding and triggers side effect on toggle -> Option A
  4. Quick Check:

    @Binding + onChange in parent = correct pattern [OK]
Quick Trick: Use onChange in parent to react to @Binding changes [OK]
Common Mistakes:
  • Placing onChange inside child instead of parent
  • Passing state without $ causing binding errors
  • Using Toggle without binding variable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes