Skip to content

Instantly share code, notes, and snippets.

@alexj70
Last active April 25, 2017 17:23
Show Gist options
  • Save alexj70/188a6d60a73551656ba85585dcc6ec79 to your computer and use it in GitHub Desktop.
Save alexj70/188a6d60a73551656ba85585dcc6ec79 to your computer and use it in GitHub Desktop.
Iteratable

Enum iteration

protocol Iteratable {}
extension RawRepresentable where Self: RawRepresentable {
    static func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
        var i = 0
        return AnyIterator {
            let next = withUnsafePointer(to: &i) {
                $0.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee }
            }
            if next.hashValue != i { return nil }
            i += 1
            return next
        }
    }
}

extension Iteratable where Self: RawRepresentable, Self: Hashable {
    static func hashValues() -> AnyIterator<Self> {
        return iterateEnum(self)
    }
    
    static func rawValues() -> [Self.RawValue] {
        return hashValues().map({$0.rawValue})
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment