多个枚举实现协议的问题 [英] Multiple enum implementing protocols questions

查看:73
本文介绍了多个枚举实现协议的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将枚举定义为对协议的确认:Eventable

I defined enums as confirming to a protocol Eventable:

protocol Eventable {
    var name: String { get }
    static var all: [Eventable] { get }
}

enum MyEnum: String, Eventable {
    case bla = "bla"
    case blu = "blu"

    var name: String {
        return self.rawValue
    }

    static var all: [Eventable] {
        return [
            MyEnum.bla,
            MyEnum.blu
        ]
    }
}

我还有其他枚举,例如MyEnum,其格式也如下:
枚举Bla:字符串,可事件{
}

I have other enums like MyEnum also under the form: enum Bla: String, Eventable { }

我有两个问题:


  1. 对于具有String数据类型的枚举,我想避免重复变量名的生成:
    变量名:String
    我不确定如何在Swift中编写它。我尝试使用 where子句,但没有成功。我该如何实现?

  1. for the enums having a String data type, I would like to avoid duplicating the generation of the variable name: var name: String I am not sure how to write that in Swift. I tried to play around with the "where" clause but not success. How can I achieve that?

当我编写枚举并符合该部分的协议时:
static var全部:[Eventable] {get}
我希望为枚举MyEnum将该变量约束为:
static var all:[MyEnum] {...}
因为现在我可以将任何元素放入Eventable中,而这并不是我所需要的。
除其他外,我尝试在协议中为其定义通用约束,但出现以下错误:

when I write my enums and conform to the protocol for that part: static var all: [Eventable] { get }. I would like that for the enum MyEnum, it constrains the variable to: static var all: [MyEnum] { ... } because for now I can put in the returned array any element being an Eventable and it's not what I need. Amongst other things, I tried to define a generic constraint in the protocol for it, but I get the following error:




协议'Eventable'只能用作通用约束,因为
具有自我或相关类型要求

Protocol 'Eventable' can only be used as a generic constraint because it has Self or associated type requirements

非常感谢您的帮助!

推荐答案

对于第二个问题,您只需要使用 Self

For your second question, you just need to use Self:

protocol Eventable {
    var name: String { get }
    static var all: [Self] { get }
}

Self 类似于 self ,只是表示当前类型。

Self, similar to self, just means "the current type".

第一个问题要难一些,因为您不能真正安全地获得枚举的所有值。有关更多信息,请参见此处。我得到的最接近的是:

The first question is a little bit harder because you can't really get all the values of an enum safely. See here for more info. The closest I got was:

extension Eventable where Self: RawRepresentable, Self.RawValue == String {
    var name: String {
        return self.rawValue
    }
}

这意味着您可以在 MyEnum 中省略 name 的声明,而不是全部的声明

This means that you can omit the declaration of name in MyEnum, but not all.

这篇关于多个枚举实现协议的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆