Neat Software
Neat Software

Follow

Neat Software

Follow

SwiftUI: Picker with Optional Binding

Neat Software's photo
Neat Software
ยทDec 14, 2022
struct ContentView: View {
    @State var selection: String?

    var body: some View {
        Picker("Select:", selection: $selection) {
            Text("None").tag(nil as String?)
            Divider()
            Text("Red").tag("R" as String?)
            Text("Green").tag("G" as String?)
            Text("Blue").tag("B" as String?)
        }
    }
}

Let's say you have a Picker in SwiftUI and want the ability to set its value to nil. In order for the optional binding to work correctly, you have to tag each item with a value casted as the optional type.

This is great for things like user preferences, which we use it extensively in all of our apps.