Skip to content

Instantly share code, notes, and snippets.

@BrandonShega
Last active March 23, 2017 18:22
Show Gist options
  • Save BrandonShega/1f534db6879d2e56970e12bb27a00c89 to your computer and use it in GitHub Desktop.
Save BrandonShega/1f534db6879d2e56970e12bb27a00c89 to your computer and use it in GitHub Desktop.
Iteratable Enum
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})
}
}
enum Direction: String, Iteratable {
case north, south, east, west
}
Direction.rawValues() //["north", "south", "east", "west"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment