0

I see this pattern a bit:

enum Stuff: Int {
        case first = 0
        case second = 1
        case third = 2
        case forth = 3

        static var count = 4

Later we will use this count variable, but what I really want is the number of case statements in the enum. Is there a way to determine this in code? (Hint, I don't want to trust the associated value)

Rob Bonner
  • 9,276
  • 8
  • 35
  • 55
  • You could make an array of all the cases and then get its `count`. Having an array of all the cases is useful in many cases actually. You'd still have to update that array every time you add / remove a case. – LinusGeffarth May 04 '18 at 14:13
  • Easy in Swift 4.2: https://stackoverflow.com/a/50177561/1187415. – Martin R May 04 '18 at 14:45

1 Answers1

0

As long as you only use integers you can add this

enum Stuff: Int {
    case first
    case second
    case third
    case forth

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

Only problem may be that this is O(n), not O(1)

link: How do I get the count of a Swift enum?

Sergio
  • 1,610
  • 14
  • 28
  • https://stackoverflow.com/a/27094913 – Martin R May 04 '18 at 14:28
  • thanks, i got it from my own project, and I did not remember how I got this solution. Apparently from stackoverflow – Kristóf Zelei May 04 '18 at 14:33
  • This won't work of a number of enums. There are 2 assumptions that you forgot to mention: Swift enum's with `Int` raw values do not have to start from 0 (even though that's the default behaviour) and their raw values can be arbitrary, they don't have to increment by 1 (even though that's the default behaviour). – Dávid Pásztor May 04 '18 at 14:34