How to Use @Binding in SwiftUI: Simple Guide with Examples
In SwiftUI, use
@Binding to create a two-way connection between a parent view's state and a child view's property. This lets the child read and update the parent's data directly, keeping UI in sync without extra code.Syntax
The @Binding property wrapper declares a reference to a value owned by another view. It allows a child view to read and write a value that is stored elsewhere, typically in a parent view's @State.
Basic syntax:
@Binding var variableName: Typeโ declares a binding property.- Pass a binding from parent using
$variableName(dollar sign prefix).
swift
struct ChildView {
@Binding var isOn: Bool
}Example
This example shows a parent view with a toggle switch controlling a boolean state. The child view receives a binding to that state and can toggle it, updating the parent's UI automatically.
swift
import SwiftUI struct ParentView: View { @State private var isOn = false var body: some View { VStack { Text(isOn ? "Switch is ON" : "Switch is OFF") ChildView(isOn: $isOn) } .padding() } } struct ChildView: View { @Binding var isOn: Bool var body: some View { Toggle("Toggle Switch", isOn: $isOn) .padding() } } struct ContentView: View { var body: some View { ParentView() } }
Output
A screen with text "Switch is OFF" and a toggle switch below it. Toggling the switch updates the text to "Switch is ON" and vice versa.
Common Pitfalls
Common mistakes when using @Binding include:
- Not passing a binding (using a normal variable) from parent to child, causing compile errors.
- Trying to create a
@Bindingwithout a source@Stateor@ObservedObject. - Forgetting to use the
$prefix when passing the binding.
Example of wrong and right usage:
swift
struct ParentView: View {
@State private var count = 0
var body: some View {
VStack {
// Wrong: passing count directly (value, not binding)
// ChildView(count: count) // Error
// Right: pass binding with $
ChildView(count: $count)
}
}
}
struct ChildView: View {
@Binding var count: Int
}Quick Reference
- @Binding: Declares a two-way connection to a value owned elsewhere.
- @State: Declares a source of truth for a value owned by a view.
- Pass binding with
$variablesyntax. - Use
@Bindingin child views to read and write parent's state.
Key Takeaways
Use @Binding to share and update state between parent and child views in SwiftUI.
Pass bindings from parent to child using the $ prefix on @State variables.
Child views with @Binding can read and write the parent's state directly.
Always ensure the binding source exists, typically as @State in the parent.
Forgetting the $ prefix or using plain variables causes compile errors.