Unlock This Episode
Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.
So, everything works exactly as it did before, but we are now allowed to opt into which fields should be bindable. This makes our domain modeling much safer by allowing us to restrict the ways certain state is allowed to be mutated.
With this in place we are now in a position to reduce even more boilerplate in our binding tools. We’ve already made great strides by not forcing us to create an action for every single piece of state that wants to be mutated via a UI binding, but we can go further.
Right now constructing a binding to a piece of state is a bit of a pain. We have to invoke the
binding method on
ViewStore, which requires passing the key path as well as the enum case of our actions that identifies where the binding action resides. Usually this can all fit on a single line, albeit a pretty intense line, but we personally like to mix in copious amounts of newlines to break up our code and so for us this binding helper makes our code quite a bit longer.
Well, luckily there’s a better way. This idea was first brought to our attention by one of our viewers, June Bash, and then over time independently by a bunch of other viewers on Twitter and in our library’s GitHub discussions. Coupling their ideas with the work we have just done on the
@BindableState wrapper we can shorten our code tremendously, and even restore some of the concise ergonomics that we know and love from vanilla SwiftUI.
Subscribe to Point-Free
Access this episode, plus all past and future episodes when you become a subscriber.
Already a subscriber? Log in
Further reducing boilerplate with... a protocol...?June Bash • Monday Feb 1, 2021
June Bash first suggested using a protocol like
BindableAction in this GitHub discussion.
Enum cases as protocol witnessesSuyash Drijan • Saturday Jan 18, 2020
The Swift Evolution proposal that made it possible for enums to conform to protocols via their case initializers.