Last active
June 22, 2017 08:22
-
-
Save ctreffs/9d115aea05cb848c1c57b4f6c181c69e to your computer and use it in GitHub Desktop.
EnumCollection Swift 3.1+
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
protocol EnumCollection {} | |
extension EnumCollection where Self: Hashable { | |
static func sequence() -> AnySequence<Self> { | |
return AnySequence { () -> AnyIterator<Self> in | |
var raw = 0 | |
return AnyIterator { | |
let `case` : Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: Self.self, capacity: 1) { $0.pointee } } | |
guard `case`.hashValue == raw else { return nil } | |
raw += 1 | |
return `case` | |
} | |
} | |
} | |
} | |
extension EnumCollection where Self: Hashable, Self: RawRepresentable { | |
static func sequence() -> AnySequence<(Self,Self.RawValue)> { | |
return AnySequence { () -> AnyIterator<(Self, Self.RawValue)> in | |
var raw = 0 | |
return AnyIterator { | |
let `case` : Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: Self.self, capacity: 1) { $0.pointee } } | |
let value = `case`.rawValue | |
guard `case`.hashValue == raw else { return nil } | |
raw += 1 | |
return (`case`, value) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment