Iterating through an Enum in Swift 3.0

前端 未结 6 470
野性不改
野性不改 2021-01-06 02:35

I have a simple enum that I would like to iterate over. For this purpose, I\'ve adopted Sequence and IteratorProtocol as shown in the code below. BTW, this can be copy/paste

6条回答
  •  庸人自扰
    2021-01-06 03:21

    If your enum is an Int based one, you can do an effective but slightly dirty trick like this.

    enum MyEnum: Int {
        case One
        case Two
    }
    
    extension MyEnum {
        func static allCases() -> [MyEnum] {
            var allCases = [MyEnum]()
            for i in 0..<10000 {
                if let type = MyEnum(rawValue: i) {
                    allCases.append(type)
                } else {
                    break
                }
            }
            return allCases
        }
    }
    

    Then loop over MyEnum.allCases()..

提交回复
热议问题