Logo for tanaschita.com

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.

Sponsorship logo
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

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.

Sponsorship logo
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

observation

swiftui

property wrappers

swift

ios

Migrating to the Observation framework in SwiftUI

Learn how to use SwiftUI's @Observable macro.

07 Aug 2023 · 5 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum