Search code examples
swiftenums

Enum: Count and list all cases (from outside!)


I've got this enum (Xcode 10/Swift 5) in its own file ("MyEnum.swift"):

enum MyEnum: Int, CaseIterable {
    case A = 0
    case B = 1
    case C = 2
    case D = 3
    case E = 4
    //Each case needs its own number and description!

    var description: String {
        switch self {
            case .A:
                return "abc"
            case .B:
                return "bcd"
            case .C:
                return "cde"
            case .D:
                return "def"
            case .E:
                return "efg"
        }
    }
}

... and want to add the descriptions to a PickerView. I know how to set up the functions for the view but I'm now stuck on counting the enum cases and adding the descriptions.

According to the documentation and different questions, adding CaseIterable is supposed to make it possible to call

MyEnum.allCases.count

... but I can only access allCases from within the enum file. From outside (so from my ViewController class) I can only call MyEnum.AllCases, which hasn't got count and, to be honest, I'm not even sure what AllCases returns exactly (it's not a normal array you can use count on).

Adding this code (source) to the enum file at least makes it possible to count the cases:

static let count: Int = {
    var max: Int = 0
    while MyEnum(rawValue: max) != .none { max += 1 }
    return max
}()

...but isn't there supposed to be an easier way to do this with Swift 4.2+?

How do I get a list of the case descriptions to fill my PickerView with (so "abc", "bcd",... - preferably without hardcoding it)?


Solution

  • I tried in 1 file:

    enum TestEnum: CaseIterable {
        case test1
        case test2
    }
    

    in another file of another class I wrote:

    let count = TestEnum.allCases.count
    

    And it works, but I noticed that when I was typing "allCases" wasn't shown

    enter image description here

    I manually needed to write it