Safer, Conciser Forms: Part 2

Episode #159 • Sep 6, 2021 • Subscriber-Only

We just made the Composable Architecture’s concise binding helpers safer, but can we make them even more concise? We’ll start with a suggestion that came from the community and employ even more Swift tricks, like dynamic member lookup, to get things even conciser than vanilla SwiftUI.

Previous episode
Safer, Conciser Forms: Part 2
Next episode

Unlock This Episode

Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.

Sign in with GitHub


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.

Reducing boilerplate with a protocol



Get started with our free plan

Our free plan includes 1 subscriber-only episode of your choice, access to 62 free episodes with transcripts and code samples, and weekly updates from our newsletter.

View plans and pricing