How do you use an enum with a Picker in SwiftUI?

← Swift answers

Make the enum CaseIterable and Identifiable, loop over allCases inside the Picker, and bind the selection to an @State value of the enum type.

enum Flavor: String, CaseIterable, Identifiable {
    case chocolate, vanilla, strawberry
    var id: Self { self }
}
 
struct FlavorPicker: View {
    @State private var flavor: Flavor = .vanilla
 
    var body: some View {
        Picker("Flavor", selection: $flavor) {
            ForEach(Flavor.allCases) { flavor in
                Text(flavor.rawValue.capitalized).tag(flavor)
            }
        }
        .pickerStyle(.menu)
    }
}

The tag must have the same type as the selection. If the selection is optional, tag each row with the optional value (.tag(Optional(flavor))) and add a row tagged nil for the empty choice.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required