Skip to content

Instantly share code, notes, and snippets.

@garohussenjian
Last active May 25, 2017 05:48
Show Gist options
  • Save garohussenjian/f140d961600191aeef9d5367b1f71d11 to your computer and use it in GitHub Desktop.
Save garohussenjian/f140d961600191aeef9d5367b1f71d11 to your computer and use it in GitHub Desktop.
Convert RawRepresentable / enum to an Array
import Foundation
protocol RawEnumerable: RawRepresentable {
static var first: Self? { get }
}
extension RawEnumerable where RawValue == Int {
static var first: Self? {
guard let first = Self(rawValue: 0) else {
fatalError("RawEnumerable must have a valid `first` case")
}
return first
}
static func cases(from startCase: Self? = Self.first, to endCase: Self? = nil) -> [Self] {
var result: [Self] = []
var rawValue = startCase?.rawValue ?? 0
let endValue = endCase?.rawValue ?? .max
while let caseValue = Self(rawValue: rawValue), rawValue <= endValue {
result.append(caseValue)
rawValue += 1
}
return result
}
}
enum MyEnum: Int, RawEnumerable {
case one, two, three, four, five, six
}
print(MyEnum.cases())
print(MyEnum.cases(from: .two))
print(MyEnum.cases(to: .three))
print(MyEnum.cases(from: .four, to: .five))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment