Last active
April 19, 2018 08:31
-
-
Save aryaxt/f5d110b01dda2abcc6a6 to your computer and use it in GitHub Desktop.
Swift enum -> Get an array of all cases
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
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