使用比较运算符扩展Int enum

时间:2017-11-23 23:23:24

标签: swift enums integer compare extension-methods

通常你有这样的Int枚举:

enum Difficulty: Int {
    case Easy = 0
    case Normal
    case Hard
}

Difficulty值具有一定的含义,我们可能希望为它们引入顺序。例如,我们需要比较的地方:

let isBonusAvailable = level.difficulty.rawVAlue <= Difficulty.Hard.rawValue

我想让这段代码更短一些:

let isBonusAvailable = level.difficulty <= .Hard

如果我将<=直接添加到Difficulty可以轻松实现。但是我想一般解决这个问题,所以我尝试了这种超级棘手的方法:

protocol RawRepresentableByInt {
    var rawValue: Int { get }
}

extension RawRepresentableByInt {
    static func <(lhs: RawRepresentableByInt, rhs: RawRepresentableByInt) -> Bool {
        return lhs.rawValue < rhs.rawValue
    }

    static func >(lhs: RawRepresentableByInt, rhs: RawRepresentableByInt) -> Bool {
        return lhs.rawValue > rhs.rawValue
    }

    static func <=(lhs: RawRepresentableByInt, rhs: RawRepresentableByInt) -> Bool {
        return lhs.rawValue <= rhs.rawValue
    }

    static func >=(lhs: RawRepresentableByInt, rhs: RawRepresentableByInt) -> Bool {
        return lhs.rawValue >= rhs.rawValue
    }
}

// Error: Extension of protocol 'RawRepresentable' cannot have an inheritance clause
extension RawRepresentable: RawRepresentableByInt where RawValue == Int  {
}

它产生编译器错误:

  

错误:协议扩展&#39; RawRepresentable&#39;不能有继承条款

我认为在Int enum的逻辑方面,没有什么是无法实现的。请帮助我欺骗Swift编译器。任何需要此类扩展的人都可以参加。

1 个答案:

答案 0 :(得分:1)

这比我想的要容易。因此,基本上,您可以使用Self而不是创建其他协议。

enum Difficulty: Int {
    case Easy = 0
    case Normal
    case Hard
}

extension RawRepresentable where RawValue: Comparable {
    static func <(lhs: Self, rhs: Self) -> Bool {
        return lhs.rawValue < rhs.rawValue
    }

    static func >(lhs: Self, rhs: Self) -> Bool {
        return lhs.rawValue > rhs.rawValue
    }

    static func <=(lhs: Self, rhs: Self) -> Bool {
        return lhs.rawValue <= rhs.rawValue
    }

    static func >=(lhs: Self, rhs: Self) -> Bool {
        return lhs.rawValue >= rhs.rawValue
    }
}

let easy = Difficulty.Easy
print(easy > .Hard) // false