-
-
Save YK-Unit/19e3ebe19204dd9b428264bad66b02a0 to your computer and use it in GitHub Desktop.
Swift enum -> Get an array of all cases
This file contains 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