Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift 3 - Enum utils
//
// Based on https://quinesoft.de/2016/05/23/swift-enumerate-iterate-enum/
//
// Usage:
//
// public enum Pies: Int, EnumerableEnum {
// case apple
// case strawberry
// case chicken
// }
//
// class MyClass {
// func demoEnumerableEnum(){
// for v in Pies.allValues() {
// print(v)
// }
// print(Pies.count())
// }
// }
protocol EnumerableEnum: RawRepresentable {
static func allValues() -> [Self]
static func count() -> Int
}
extension EnumerableEnum where RawValue == Int {
static func allValues() -> [Self] {
var index = 0
var array = [Self]()
while let element = Self(rawValue: Int(index)) {
array.append(element)
index += 1
}
return array
}
static func count() -> Int {
var index = 0
while let _ = Self(rawValue: Int(index)) {
index += 1
}
return index
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.