Last active
September 28, 2017 09:17
-
-
Save wanbok/68819372a289a5c805204eaecc3b67e3 to your computer and use it in GitHub Desktop.
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
// | |
// EnumCollection.swift | |
// Created by Wanbok Choi on 2017. 4. 12.. | |
// | |
protocol EnumCollection: Hashable { | |
static var iterator: AnyIterator<Self> { get } | |
static var allValues: [Self] { get } | |
} | |
extension EnumCollection { | |
static var iterator: AnyIterator<Self> { | |
var raw = 0 | |
return AnyIterator { | |
let next = withUnsafeBytes(of: &raw) { $0.load(as: `Self`.self) } | |
guard next.hashValue == raw else { return nil } | |
raw += 1 | |
return next | |
} | |
} | |
static var allValues: [Self] { | |
return Array(self.iterator) | |
} | |
} | |
/// Example | |
enum TestEnum: String, EnumCollection { | |
case one = "one" | |
case two = "two" | |
case three = "three" | |
} | |
TestEnum.allValues // [one, two, three] | |
for number in TestEnum.iterator { | |
print(number) | |
} // print one, two, three | |
TestEnum.iterator.forEach { | |
print($0) | |
} // print one, two, three | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment