Both property wrappers Binding and Bindable in SwiftUI allow you to create bindings, they sound similar but behave differently.
A property wrapper allows you to create a two-way connection between a property that stores data and a view that displays and changes the data. You can pass a value from a parent view to a child view, and any changes made by the child view will be reflected in the parent view.
struct ParentView: View {
@State var name: String = ""
var body: some View {
ChildView(name: $name)
}
}
struct ChildView: View {
@Binding var name: String
var body: some View {
TextField("Enter your name", text: $name)
}
}
A property wrapper to create bindings to mutable properties of a data model object that conforms to the Observable protocol.
@Observable class Habit: Identifiable {
var title = "Quit smoking"
var positive = true
}
struct HabitView: View {
@Bindable var habit: Habit
var body: some View {
Form {
TextField("Title", text: $habit.title)
Toggle("Positive", isOn: $habit.positive)
}
}
}