Showing a Swift Enum’s Values in a SwiftUI Picker
Swift enums let you create your own data types with a limited number of possible values. You may want to use a picker in a SwiftUI app to choose one of the enum’s values. Filling a picker with an enum’s values requires you to do two things.
- Make the enum conform to the
CaseIterable
protocol. - Wrap the picker in a
ForEach
block, supplying an array of the enum’s values.
Conforming to CaseIterable
Your Swift enum must conform to the CaseIterable
protocol to get an array of the enum’s values. In most cases, conforming to CaseIterable
is easy. Add CaseIterable
after a colon when creating the enum. The following code shows a simple enum that conforms to CaseIterable
:
enum IssuePriority: Int, CaseIterable {
case low = 1
case medium = 2
case high = 3
// Convert to string to display in menus and pickers.
func stringValue() -> String {
switch(self) {
case .low:
return "Low"
case .medium:
return "Medium"
case .high:
return "High"
}
}
}
By conforming to CaseIterable
, the enum gets an allCases
property that contains an array of the enum’s values. Use the property in a picker or any other SwiftUI view that shows an array of items.
Wrap the Picker in a ForEach Block
To provide picker items for each enum value, wrap the picker in a ForEach
block. Supply the enum’s allCases
property in the ForEach
block. Create a Text
view or whatever view you want for the picker item. The following code demonstrates how to create a picker with items for each value in the IssuePriority
enum from the previous section:
@State var issuePriority: IssuePriority = .low
Picker("Issue Priority:", selection: $issuePriority) {
ForEach(IssuePriority.allCases, id: \.self) { priority in
let menuText = priority.stringValue()
Text("\(menuText)")
.tag(priority)
}
}