Enums are a natural fit for Picker views in SwiftUI. They’re structured, type-safe, and easy to loop through. In this guide, we’ll help you start with creating a SwiftUI Picker Enum while giving a heads-up of different protocols with examples for easier understanding.
Define an Enum for Your Options
Let’s say you want to select a notification sound. For this, we’ll create an enum that lists all available sound options:
enum NotificationSound {
case chime
case bell
case echo
}
But to use this enum in a Picker, we need to do a bit more. SwiftUI’s Picker relies on looping and identifying values, and enums don’t support that out of the box. That’s where a few simple protocol conformances come in.
Why These Protocols Are Needed?
CaseIterable: Makes the Enum Loopable
The ForEach used inside a Picker needs something it can iterate over. Conforming your enum to CaseIterable automatically adds an allCases property containing every case.
enum NotificationSound: CaseIterable {
case chime, bell, echo
}
// Now you can do:
NotificationSound.allCases // [.chime, .bell, .echo]
Identifiable: Makes Each Case Trackable
SwiftUI’s ForEach also needs to know how to uniquely identify each element — especially for UI updates. For enums without associated values, this is easy. Just conform to Identifiable and use the enum case itself as the id.
enum NotificationSound: CaseIterable, Identifiable {
case chime, bell, echo
var id: Self { self }
}
CustomStringConvertible: Makes the Label User-Friendly
By default, using Text(“\(value)”) in SwiftUI will print the raw case name like chime. To display something more readable, you can conform to CustomStringConvertible and provide a description:
enum NotificationSound: CaseIterable, Identifiable, CustomStringConvertible {
case chime, bell, echo
var id: Self { self }
var description: String {
switch self {
case .chime: return "Chime"
case .bell: return "Bell"
case .echo: return "Echo"
}
}
}
Build the SwiftUI Picker View
With the enum fully set up, here’s how you create the Picker:
struct SoundPickerView: View {
@State private var selectedSound: NotificationSound = .chime
var body: some View {
Picker("Notification Sound", selection: $selectedSound) {
ForEach(NotificationSound.allCases) { sound in
Text(sound.description).tag(sound)
}
}
.pickerStyle(.wheel)
}
}
This shows a scrollable list of enum cases, displays a readable label for each, and updates selectedSound as you make a choice.
Choosing the Right Picker Style
SwiftUI gives you flexibility in how your Picker is presented. The most common styles are:
.wheel
: Good for settings-style UIs, especially in compact layouts like iPhone..segmented
: Ideal for toggling between a small number of options. It replaces the Picker with a horizontal switcher..menu
: Offers a dropdown-like menu, useful when space is limited.