Implement Two-Way UIKit Binding in Vanilla Swift

Avoid third parties if you can!

Photo by Matthew Henry

Prerequisites:

Terminology

Binding: A technique that binds data sources from the provider and consumer together and synchronizes them MVVM: An architecture pattern consisiting of Model, View and View-Model Observable: An emitter of notifications of a change Observer: An object that wishes to be notified when the state of another object changes. Subscribe: An observer lets a subject know that it wants to be informed of changes through a process called subscribing Subscriber: A term meaning Observer Type: A representation of the tyoe of data that can be processed, for example Integer or String

Loose coupling

The open-closed principle says that implementation should hide behind an interface — that is; loose coupling.

The project

I’m going to create a rather dull project that has three UITextField components on it, each of which will implement two-way binding in slightly different ways. This finished project looks just like the following image:

The completed project

The first UITextField Observing a String, AKA one-way binding fixed to be two-way

The UITextField called firstTF is connected to a String in the ViewModel, but in this case we aren't going to use a simple String - this is going to be an Observable - that is, a type that can be observed, and I've constructed this as a class.

The second UITextField

The secondTF uses a bind function (which is actually a two-way binding) as:

The third example

We can use keypaths to make a MakeBindable type that we will use in place of the Observable type we used before:

Improving the MakeBindable class

We will need a function to show us the current value

Conclusion

Two-way binding without using RxSwift or similar? That's interesting as we can see how the functions should work, and we can even have a great new use for KeyPaths.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store