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
协议??
答案 0 :(得分:1)
当<
的关联RawRepresentable
为RawValue
时,您只需为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))}}
中,瞧瞧!