SwiftUI – How to display an Enum in a Picker

By | 17/02/2021

In this post, we will see how to display an Enum in a Picker.
First of all, we start creating a new project called ViewEnum where we will add a file called LstCars, used to define an Enum consisting of a list of car brands:

[LSTCARS.SWIFT]

// with the CaseIterable protocol, we will
// have the list of all enum's cases
enum LstCars: Int, CaseIterable {
    case ferrari = 0
    case porsche = 1
    case lamborghini = 2
    case pagani = 3
    case mclaren = 4

    init(type: Int) {
        switch type {
        case 0: self = .ferrari
        case 1: self = .porsche
        case 2: self = .lamborghini
        case 3: self = .pagani
        case 4: self = .mclaren
        default: self = .ferrari
        }
    }

    // with description, we could display a detailed description
    var description: String {
        switch self {
        case .ferrari: return "Ferrari - LaFerrari"
        case .porsche: return "Porsche - Panamera"
        case .lamborghini: return "Lamborghini - Aventador"
        case .pagani: return "Pagani - Huayra"
        case .mclaren: return "McLaren - 720S"
        }
    }
}



Finally, we define a Picker in the file ContentView where will display the LstCars enum:

[CONTENTVIEW.SWIFT]

import SwiftUI

struct ContentView: View {
    @State private var selectedCar = LstCars.ferrari
    var body: some View {
        Picker("Choose a car", selection: $selectedCar)
        {
            ForEach(LstCars.allCases, id: \.self)
            { carType in
                Text(carType.description)
            }
        }
        Text("You have selected \(selectedCar.description)")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}



Now, if we run the application, this will be the result:



Leave a Reply

Your email address will not be published. Required fields are marked *