Created
December 6, 2019 02:20
-
-
Save devmjun/cce594c02d7c97bbd0267297f6caf1e1 to your computer and use it in GitHub Desktop.
iterable 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
public protocol EnumCollection: Hashable { | |
static func cases() -> AnySequence<Self> | |
static var allValues: [Self] { get } | |
} | |
public extension EnumCollection { | |
public static func cases() -> AnySequence<Self> { | |
return AnySequence { () -> AnyIterator<Self> in | |
var raw = 0 | |
return AnyIterator { | |
let current: Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: self, capacity: 1) { $0.pointee } } | |
guard current.hashValue == raw else { | |
return nil | |
} | |
raw += 1 | |
return current | |
} | |
} | |
} | |
public static var allValues: [Self] { | |
return Array(self.cases()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment