Last active
March 23, 2017 18:22
-
-
Save BrandonShega/1f534db6879d2e56970e12bb27a00c89 to your computer and use it in GitHub Desktop.
Iteratable Enum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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