难道这些还不够吗?
enum State: Int, Comparable {
case Loading
case Loaded
case Resolved
case Processed
}
func < (lhs: State, rhs: State) -> Bool {
return lhs.rawValue < rhs.rawValue
}
let state = State.Resolved
state > .Loaded // true
请注意,仅<
需要实施,因为enum
s 已经相等了...
一般来说,可比性enums
独立于它们的原始值(如果有)——例如:
enum State: Comparable {
case Good
case Bad
}
func < (lhs: State, rhs: State) -> Bool {
return lhs == .Bad && rhs == .Good
}
let state = State.Good
state > .Bad // true
关于第二个想法, Swift 确实允许我们扩展RawRepresentable
具有 @devios 正在寻找的确切效果的协议:
/// Extends all `RawRepresentable` enums with `Comparable` raw values,
/// such as `enum E : Int` or `enum E : String`...
///
public func < <E: RawRepresentable where E.RawValue : Comparable> (lhs: E, rhs: E) -> Bool {
return lhs.rawValue < rhs.rawValue
}
将其隐藏在扩展库中的某个位置后,您所需要做的就是通过将您的类型声明为来明确选择加入Comparable
:
enum N: Int, Comparable {
case Zero, One, Two, Three
}
enum S: String, Comparable {
case A, B, C, D
}
let n: N = .Two
n > .One // true
let ss: [S] = [.B, .A, .D, .C].sort() // [A, B, C, D]
如果通用行为不适合特定类型,这仍然允许您提供具体的实现:
func < (lhs: S, rhs: S) -> Bool {
return rhs.hashValue < lhs.hashValue // inverting the ordering
}
let ss: [S] = [.B, .A, .D, .C].sort() // [D, C, B, A]