How to map a SwiftUI state to a binding of a different type
Learn how to create custom SwiftUI bindings.
05 Jun 2023 · 2 min read
When working with states and bindings in SwiftUI, we sometimes might have a use case where we need to map a state type to a different binding type. Let's look at an example and see how to do that.

Imagine, we have a SwiftUI view with a selection from a list and a button to save that selection. The button should be disabled as long as the user hasn't made a selection yet:
struct SaveView: View {@State private var selectedOption: SelectionOption?var body: some View {VStack {SelectionView(selectedOption: $selectedOption)Spacer()SaveButton(action: {}, isDisabled: ???)}}}
The isDisabled parameter is of type Bindable<Bool> so we need some kind of mapping from the selectedOption state property. For that case, we can initialize a Binding as follows:
SaveButton(action: {}, isDisabled: Binding(get: { selectedOption == nil },set: { _ in }))
As shown above, we can create a custom binding using the Binding type which takes a get and a set closure. This is really useful when we need to add custom logic to a binding.

Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips