Bindable
A property wrapper type that supports creating bindings to the mutable properties of observable objects.
Declaration
@dynamicMemberLookup @propertyWrapper struct Bindable<Value>Overview
Use this property wrapper to create bindings to mutable properties of a data model object that conforms to the Observable protocol. For example, the following code wraps the book input with @Bindable. Then it uses a TextField to change the title property of a book, and a Toggle to change the isAvailable property, using the $ syntax to pass a binding for each property to those controls.
@Observable
class Book: Identifiable {
var title = "Sample Book Title"
var isAvailable = true
}
struct BookEditView: View {
@Bindable var book: Book
@Environment(\.dismiss) private var dismiss
var body: some View {
Form {
TextField("Title", text: $book.title)
Toggle("Book is available", isOn: $book.isAvailable)
Button("Close") {
dismiss()
}
}
}
}You can use the Bindable property wrapper on properties and variables to an Observable object. This includes global variables, properties that exists outside of SwiftUI types, or even local variables. For example, you can create a @Bindable variable within a view’s body:
struct LibraryView: View {
@State private var books = [Book(), Book(), Book()]
var body: some View {
List(books) { book in
@Bindable var book = book
TextField("Title", text: $book.title)
}
}
}The @Bindable variable book provides a binding that connects TextField to the title property of a book so that a person can make changes directly to the model data.
Use this same approach when you need a binding to a property of an observable object stored in a view’s environment. For example, the following code uses the Environment property wrapper to retrieve an instance of the observable type Book. Then the code creates a @Bindable variable book and passes a binding for the title property to a TextField using the $ syntax.
struct TitleEditView: View {
@Environment(Book.self) private var book
var body: some View {
@Bindable var book = book
TextField("Title", text: $book.title)
}
}