Iterating through an Enum in Swift 3.0

前端 未结 6 467
野性不改
野性不改 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:25

    Note that Martin’s solution can be refactored as a protocol:

    import Foundation
    
    protocol EnumSequence
    {
        associatedtype T: RawRepresentable where T.RawValue == Int
        static func all() -> AnySequence
    }
    extension EnumSequence
    {
        static func all() -> AnySequence {
            return AnySequence { return EnumGenerator() }
        }
    }
    
    private struct EnumGenerator: IteratorProtocol where T.RawValue == Int {
        var index = 0
        mutating func next() -> T? {
            guard let item = T(rawValue: index) else {
                return nil
            }
            index += 1
            return item
        }
    }
    

    Then, given an enum

    enum Fruits: Int {
        case apple, orange, pear
    }
    

    you slap the protocol and a typealias:

    enum Fruits: Int, EnumSequence {
        typealias T = Fruits
        case apple, orange, pear
    }
    
    Fruits.all().forEach({ print($0) }) // apple orange pear
    

提交回复
热议问题