In Swift, when an enum conforms to CaseIterable, "The synthesized allCases collection provides the cases in order of their declaration."
I would like to sort an array of CaseIterable enum cases, which means conforming to Comparable. Can I access this same order of declaration to determine how such objects should be sorted?
If not, is my implementation of < below reasonable?
enum MyEnum: CaseIterable, Comparable {
case one, two, three
}
static func < (lhs: MyEnum, rhs: MyEnum) -> Bool {
guard let lhsIndex = allCases.firstIndex(of: lhs), let rhsIndex = allCases.firstIndex(of: rhs) else {
fatalError("`MyEnum`'s implementation of `Comparable.<` found a case that isn't present in `allCases`.")
}
return lhsIndex < rhsIndex
}
Finally, is it possible to go one step further and make CaseIterable itself conform to Comparable this way? Any reason this would be a bad idea?