Iterating through an Enum in Swift 3.0

前端 未结 6 466
野性不改
野性不改 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条回答
  •  梦毁少年i
    2021-01-06 03:28

    This looks so much simpler:

    public protocol EnumSequence {
        init?(rawValue: Int)
    }
    
    public extension EnumSequence {
    
        public static var items: [Self] {
            var caseIndex: Int = 0
            let interator: AnyIterator = AnyIterator {
                let result = Self(rawValue: caseIndex)
                caseIndex += 1
                return result
            }
            return Array(interator)
        }
    }
    

提交回复
热议问题