Picker style .menu doesn't handle nil

Here's the code...

import SwiftUI

enum Side: String {
    case left
    case right
}

struct SideView: View {
    @State private var name: String = ""
    @State private var side: Side? = nil

    var body: some View {
        NavigationStack {
            Form {
                Section {
                    TextField("Name", text: $name)
                    Picker("Side", selection: $side) {
                        Text("Left").tag(Side.left as Side?)
                        Text("Right").tag(Side.right as Side?)
                    }
                    .pickerStyle(.menu) // displays with "Left" selected even though side is nil
//                    .pickerStyle(.inline) // all the other styles work as expected, nothing initially selected
//                    .pickerStyle(.palette)
//                    .pickerStyle(.navigationLink)
                }
            }
        }
    }
}

#Preview("SideView") {
    SideView()
}

Even though side is nil the .menu style displays with "Left" selected. Try any of the other styles. They all display with nothing initially selected. As they should when side is nil.

This seems like a bug and I've submitted feedback. ID: FB21685273

Whether it's a bug or not has anyone worked around this?

Hello murraysagal,

Thanks for your question. This might be intentional behavior of the .menu picker style. Like with HTML <select> dropdown, if no value is provided via the binding, then the first option is chosen by default, at least in the UI.

A potential workaround might be to provide a .hidden() option with an explicitly empty value (nil as Side? in your case), but it will still show a blank option that is initially selected when the user first taps on the menu.

So it might be helpful to reconsider the design of using a different picker style that does not display an initially selected state after the user interacts with it (e.g. opening the dropdown).

Thank you for your patience,

Richard Yeh  Developer Technical Support

Picker style .menu doesn't handle nil
 
 
Q