Skip to content

Instantly share code, notes, and snippets.

@ctreffs
Last active June 22, 2017 08:22
Show Gist options
  • Save ctreffs/9d115aea05cb848c1c57b4f6c181c69e to your computer and use it in GitHub Desktop.
Save ctreffs/9d115aea05cb848c1c57b4f6c181c69e to your computer and use it in GitHub Desktop.
EnumCollection Swift 3.1+
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