Skip to content

Instantly share code, notes, and snippets.

@YK-Unit
Forked from aryaxt/RawRepresentableExtension
Created April 9, 2018 03:18
Show Gist options
  • Save YK-Unit/19e3ebe19204dd9b428264bad66b02a0 to your computer and use it in GitHub Desktop.
Save YK-Unit/19e3ebe19204dd9b428264bad66b02a0 to your computer and use it in GitHub Desktop.
Swift enum -> Get an array of all cases
extension RawRepresentable where Self: Hashable {
private static func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
var index = 0
let closure: () -> T? = {
let next = withUnsafePointer(to: &index) {
$0.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee }
}
guard next.hashValue == index else { return nil }
index += 1
return next
}
return AnyIterator(closure)
}
static var allValues: [Self.RawValue] {
return iterateEnum(self).map { $0.rawValue }
}
static var allCases: [Self] {
return iterateEnum(self).map { $0 }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment