SwiftUI Picker with Optional Binding
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 can tag
each item with the value casted as the optional type.
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?)
}
}
}
This is great for things like user preferences, which we use it extensively in all of our apps at Neat Software.