Skip to content

Instantly share code, notes, and snippets.

@tomlobato
Last active February 11, 2018 09:18
Show Gist options
  • Save tomlobato/5923a82bbb41d9d1d2d2e26683fa3c4c to your computer and use it in GitHub Desktop.
Save tomlobato/5923a82bbb41d9d1d2d2e26683fa3c4c to your computer and use it in GitHub Desktop.
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