Skip to content

Instantly share code, notes, and snippets.

@aryaxt
Last active April 19, 2018 08:31
Show Gist options
  • Save aryaxt/f5d110b01dda2abcc6a6 to your computer and use it in GitHub Desktop.
Save aryaxt/f5d110b01dda2abcc6a6 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