The only piece of the protocol that isn't implemented is the var boundValue: BoundType member. As we're implementing on UITextField, BoundType will be String?, as it is the type of the string property:
extension UITextField: Bindable {
var boundValue: String? {
get { return self.text }
set { self.text = newValue }
}
}
We can now use it all, with the following example:
let observable = Observable<String?>("Let's get started")
var textField = UITextField(frame: .zero)
textField.bind(observable)
print("1. \(textField.text!)")
observable.value = "Are you Ready?"
print("2. \(textField.text!)")
textField.text = "YES!"
textField.sendActions(for: .valueChanged)
print("3. \(observable.value!)")
// Output:
1. Let's get started // the text field value has been automatically set
2. Are you Ready? // Updating the value in the observable, updates the text
3. YES! // Setting the value in field, updates the model
This concludes the implementation of the Observable class and the Binding protocol. In the next section, we'll look at how to use two-way binding alongside a complex form.