Skip to content

Instantly share code, notes, and snippets.

@wanbok
Last active September 28, 2017 09:17
Show Gist options
  • Save wanbok/68819372a289a5c805204eaecc3b67e3 to your computer and use it in GitHub Desktop.
Save wanbok/68819372a289a5c805204eaecc3b67e3 to your computer and use it in GitHub Desktop.
//
// 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