Consider a SwiftUI parent view passing a @State variable as a @Binding to a child view. What is the effect when the child view modifies this @Binding variable?
struct ParentView: View {
@State private var count = 0
var body: some View {
ChildView(count: $count)
}
}
struct ChildView: View {
@Binding var count: Int
var body: some View {
Button("Increment") {
count += 1
}
}
}Think about how @Binding connects child and parent state in SwiftUI.
@Binding creates a two-way connection between the parent and child views. When the child modifies the @Binding variable, it updates the parent's @State variable, causing the UI to refresh.
Which of the following is the correct syntax to declare a @Binding variable named isOn of type Bool in a SwiftUI child view?
Remember that @Binding is a property wrapper used to declare a binding variable.
The correct syntax uses the @Binding property wrapper with var. Option C declares a Binding type but not as a property wrapper, which is incorrect for a child view's binding variable.
In SwiftUI, after a child view modifies a @Binding variable, when does the parent view re-render?
Think about how SwiftUI batches view updates for performance.
SwiftUI batches state changes and schedules view updates after the current run loop completes to optimize performance. So the parent view re-renders shortly after the @Binding variable changes, not immediately.
Given the code below, why does tapping the button not update the parent view's text?
struct ParentView: View {
@State private var text = "Hello"
var body: some View {
ChildView(text: text)
}
}
struct ChildView: View {
@Binding var text: String
var body: some View {
Button("Change") {
text = "World"
}
}
}Check how the parent passes the variable to the child.
The parent must pass a binding using the $ prefix (e.g., $text) to connect the child's @Binding variable. Passing just text sends a copy, so changes in the child don't affect the parent.
Why is @Binding preferred for passing data from a parent to a child view when the child needs to modify the parent's state?
Think about how data flows and updates between views in SwiftUI.
@Binding allows the child view to read and write the parent's state directly, enabling synchronized UI updates without duplicating state or complex callbacks.