Search code examples
swiftenumsswift2introspection

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)
}

Solution

  • You can write a generic struct that provide that iteration ability. In example below the enum raw values must start with 0 (it does it by default) and have no gaps between raw values (can't have raw values such as 0,1,2,3,5 -- 4 is missing)

    public struct EnumGenerator<T> : GeneratorType, SequenceType {
        private let enumInit: Int -> T?
        private var i: Int = 0
        public mutating func next() -> T? { return enumInit(i++) }
        public init(_ initFunc: Int -> T?){ self.enumInit = initFunc}
    }
    
    enum HeaderStyles:Int{
        case h1
        case h2
        case h3
    }
    
    for item in EnumGenerator(HeaderStyles.init){
        print(item)
    }