Created
July 5, 2017 07:57
-
-
Save acalism/440f58badff851af49aae45c8b7bb510 to your computer and use it in GitHub Desktop.
如何枚举enum类型的所有case
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
protocol EnumCollection : Hashable {} | |
extension EnumCollection { | |
static func cases() -> AnySequence<Self> { | |
typealias S = Self | |
return AnySequence { () -> AnyIterator<S> in | |
var raw = 0 | |
return AnyIterator { | |
let current : Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: S.self, capacity: 1) { $0.pointee } } | |
guard current.hashValue == raw else { return nil } | |
raw += 1 | |
return current | |
} | |
} | |
} | |
} | |
enum E : EnumCollection { | |
case A, B, C | |
} | |
// example | |
Array(E.cases()) // [A, B, C] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment