具有可比较原始值的Swift枚举是否可以自动合成可比较协议实现?

时间:2019-02-16 08:57:11

标签: swift

Swift可以自动为结构和枚举综合Equatable实现。同样,我也想使枚举也自动符合Comparable协议。

这就是我所做的:

enum RoyalRank: UInt8 { 
  case emperor = 3
  case king    = 2
  case duke    = 1
}

let e = RoyalRank.emperor
let k = RoyalRank.king
print(e > k)

但是,它当然不会编译。我收到以下错误:

error: cannot convert value of type 'RoyalRank' to expected argument type 'UInt8'
print(e > k)
      ^
       .rawValue

我有什么办法可以使枚举自动地符合Comparable协议??

1 个答案:

答案 0 :(得分:1)

<的关联RawRepresentableRawValue时,您只需为Comparable提供extension RawRepresentable where RawValue : Comparable { static func < (lhs: Self, rhs: Self) -> Bool { return lhs.rawValue < rhs.rawValue } } enum RoyalRank: UInt8, Comparable { case emperor = 3 case king = 2 case duke = 1 } let e = RoyalRank.emperor let k = RoyalRank.king print(e > k) 运算符的默认实现:

Comparable

enum添加到您的import UIKit import PlaygroundSupport struct Demo { let omegaMax = 10.0 let omegaC = 1.0 var omegaSignal:Double {get {return 0.1 * omegaC}} var dOmega:Double {get {return 0.1 * omegaSignal}} var omegaArray:[Double] {get {return Array(stride(from: 0.0, through: omegaMax, by: dOmega))}} 中,瞧瞧!