Skip to content

Instantly share code, notes, and snippets.

@sukov
Created July 2, 2019 22:06
Show Gist options
  • Save sukov/06bfe301f70775d702d8deecbfea4e9b to your computer and use it in GitHub Desktop.
Save sukov/06bfe301f70775d702d8deecbfea4e9b to your computer and use it in GitHub Desktop.
CaseIterable for older swift versions
#if !swift(>=4.2)
public protocol CaseIterable {
associatedtype AllCases: Collection where AllCases.Element == Self
static var allCases: AllCases { get }
}
extension CaseIterable where Self: Hashable {
static var allCases: [Self] {
return [Self](AnySequence { () -> AnyIterator<Self> in
var raw = 0
var first: Self?
return AnyIterator {
let current = withUnsafeBytes(of: &raw) { $0.load(as: Self.self) }
if raw == 0 {
first = current
} else if current == first {
return nil
}
raw += 1
return current
}
})
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment