为任意的、基于整数的枚举定义 Swift 协议

Nic*_*ari 6 enums protocols swift rawrepresentable

我有这个代表颜色的枚举,并且我添加了几种方法来方便地获取基于原始原始值的算术运算的新实例:

enum Color : Int
{
    case Red = 0
    case Green
    case Blue

    case Cyan
    case Magenta
    case Yellow


    static func random() -> Color
    {
        return Color(rawValue: Int(arc4random_uniform(6)))!
    }

    func shifted(by offset:Int) -> Color
    {
        return Color(rawValue: (self.rawValue + offset) % 6)!
        // Cyclic: wraps around
    }
}
Run Code Online (Sandbox Code Playgroud)

(这可以追溯到旧的枚举只是 int 常量)

问题是,我还有其他几个基于 int 的枚举,我想在其中引入类似的功能,但不重复代码。

我想我应该在RawRepresentablewhere上定义一个协议扩展RawValue == Int

extension RawRepresentable where RawValue == Int
{
Run Code Online (Sandbox Code Playgroud)

...但这就是我对语法的理解结束的地方。

理想情况下,我想要一个返回案例数量的静态方法,并提供一个考虑到这一点的两个random()shifted(_:)以上的默认实现(而不是这里的硬编码 6)。

结论:我接受了 Zoff Dino 的回答。尽管Rob Napier 给出的答案正是我所要求的,但结果证明我所要求的设计毕竟不是最优雅的设计,而另一个答案提出了更好的方法。不过,我对这两个答案都投了赞成票;谢谢大家。

Cod*_*ent 5

您应该扩展您的自定义协议而不是RawRepresentable. 尝试这个:

protocol MyProtocol {
    static var maxRawValue : Int { get }

    static func random() ->  Self
    func shifted(by offset: Int) -> Self
}

enum Color : Int, MyProtocol
{
    case Red = 0
    case Green
    case Blue

    case Cyan
    case Magenta
    case Yellow

    // The maximum value of your Int enum
    static var maxRawValue: Int {
        return Yellow.rawValue
    }
}

extension MyProtocol where Self: RawRepresentable, Self.RawValue == Int {
    static func random() -> Self {
        let random = Int(arc4random_uniform(UInt32(Self.maxRawValue + 1)))
        return Self(rawValue: random)!
    }

    func shifted(by offset: Int) -> Self {
        return Self(rawValue: (self.rawValue + offset) % (Self.maxRawValue + 1))!
    }
}

let x = Color.random()
let y = x.shifted(by: 1)
Run Code Online (Sandbox Code Playgroud)