ylliX - Online Advertising Network How to get all enum values in Swift? - Yet Another Programmer's Blog

How to get all enum values in Swift?

So you made brand new and shiny enum, and want to use it in f.e. picker? To achieve this you need to prepare array of strings which every picker can use. How to do it?

It’s quite simple. All you have to do is add CaseIterable protocol to your enum. Like this:

enum EventType: Int, CaseIterable {
    case human = 1
    case vehicle = 2
    case animal = 3
    case other = 4
    
    var eventName: String {
        switch self {
        case .human:
            return "human"
        case .vehicle:
            return "vehicle"
        case .animal:
            return "animal"
        case .other:
            return "other"
        }
    }
}

Then in your ViewController add:

var strings = [String]() {
    didSet {
        picker.reloadAllComponents()
    }
}

The last part is generating strings array from our enum values:

strings = EventType.allCases.map { $0.eventName }

If you want to play around with this, grab XCode 10.2 Playground from my GitHub https://github.com/blastar/EnumPicker

Leave a Reply