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