Binding a Picker's Selection to an Optional State

Something that took me some time to find a solution to was when I had a Picker that was bound to a State property that was initially nil, whenever I selected a value from that Picker, the value would never be selected. This baffled me, as there were no compiler errors or messages in the console.

I also noticed that changing my State to a non-optional type, and giving a default value inside .onAppear() fixed it for me, but I didn’t want the Picker to have a default value. In my case, the user would need to select the country themselves.

import SwiftUI

struct FormView: View {
    @ObservedObject var model: Model
    @State private var country: Country?
    
    var body: some View {
        Form {
            Picker(selection: $country, label: Text("Country")) {
                ForEach(model.countries) { country in
                    Text(country.name).tag(country)
                }
            }
        }
    }
}

The Solution#

Thankfully the solution was really simple. I had to cast the tag to the same optional type that my State property was. As you can see in the code snippet below, adding as Country? was all that was needed.

import SwiftUI

struct FormView: View {
    @ObservedObject var model: Model
    @State private var country: Country?
    
    var body: some View {
        Form {
            Picker(selection: $country, label: Text("Country")) {
                ForEach(model.countries) { country in
                    Text(country.name).tag(country as Country?)
                }
            }
        }
    }
}

Conclusion#

If this tutorial helped you in any way, I’d really appreciate a share on Twitter. You can reach out to me via Twitter if you have any questions, or to show me what you’ve been up to!