Skip to content

Instantly share code, notes, and snippets.

@devmjun
Created December 6, 2019 02:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devmjun/cce594c02d7c97bbd0267297f6caf1e1 to your computer and use it in GitHub Desktop.
Save devmjun/cce594c02d7c97bbd0267297f6caf1e1 to your computer and use it in GitHub Desktop.
iterable enum case
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