Created
July 2, 2019 22:06
-
-
Save sukov/06bfe301f70775d702d8deecbfea4e9b to your computer and use it in GitHub Desktop.
CaseIterable for older swift versions
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
#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