gpt4 book ai didi

swift - 使用比较运算符扩展 Int 枚举

转载 作者:行者123 更新时间:2023-11-28 06:08:31 32 4
gpt4 key购买 nike

你经常有这样的 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 .但我想从总体上解决这个问题,所以我尝试了这种 super 棘手的方法:

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 {
}

它会产生编译错误:

Error: Extension of protocol 'RawRepresentable' cannot have an inheritance clause

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

最佳答案

这比我想象的要容易。所以,基本上您可以使用 Self 而不是创建额外的协议(protocol)。

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

关于swift - 使用比较运算符扩展 Int 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47464446/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com