Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Introspection and iteration on an Enum

Is it possible to programatically find out how many "cases" an Enum has in Swift 2 and iterate over them?

This code doesn't compile, but it gives yo an idea of what I'm trying to achieve:

enum HeaderStyles{

    case h1
    case h2
    case h3
}

for item in HeaderStyles{
    print(item)
}
like image 205
cfischer Avatar asked Jan 07 '23 16:01

cfischer


1 Answers

The easiest way to iterate over all cases is to make a computed property which returns an Array of them:

enum SomeEnum {
    case Zero, One, Two

    static var allCases: [SomeEnum] {
        return [.Zero, .One, .Two]
    }
}

If you want an automatic array you could use Int as rawValue so you don't have to change any code if you add an additional case:

Swift 3/4: ++ and -- were removed and anyGenerator was renamed to AnyIterator

enum SomeEnum: Int {
    case Zero, One, Two

    static var allCases: [SomeEnum] {
        var i = 0
        return Array(AnyIterator{
            let newEnum = SomeEnum(rawValue: i)
            i += 1
            return newEnum
        })
    }
}

Swift 2

enum SomeEnum: Int {
    case Zero, One, Two

    static var allCases: [SomeEnum] {
        var i = 0
        return Array(anyGenerator{ SomeEnum(rawValue: i++) })
    }
}

In both cases you would use it like this:

for num in SomeEnum.allCases {
    // ...
}
like image 180
Qbyte Avatar answered Jan 16 '23 01:01

Qbyte