swift – 你可以扩展枚举吗?

我使用枚举来存储这样的字符串值:
enum Animals: String {
        case descCat = "I has attitude"
        case descDog = "how can I help"
        case descGator = "I will eat you"
        var s: String {
            get {
                return self.rawValue as String
            }
        }
    }

然后我访问他们:

print("Dogs be like:" + Animals.descDog.s)

我的问题是可以像任何其他struct或对象一样扩展枚举,所以我不必为每个枚举添加var s:String {}属性

您要为其原始值是字符串的所有枚举添加属性?这听起来像是受约束的协议扩展的情况!
extension RawRepresentable where RawValue == String {
    var description: String {
        return rawValue
    }
}

这是因为具有原始值的所有枚举自动符合RawRepresentable协议,并且所述协议具有关联的类型RawValue,它告诉您原始值的类型。

现在你的动物枚举会自动继承它:

print(Animals.descCat.description) // -> "I has attitude"

请注意,字符串枚举本身已经是customstringconvertible,因此它们已经具有描述属性(返回枚举大小写的名称),并且您的代码不会覆盖它:

print(Animals.descCat) // -> "descCat"

如果您希望您的描述覆盖认值,只需添加一个customstringconvertible一致性声明到您的枚举:

private enum Animals: String,customstringconvertible { /*...*/ }
print(Animals.descCat) // -> "I has attitude"

您也可以扩展这个想法来涵盖其他原始值类型。例如:

extension RawRepresentable where RawValue: customstringconvertible {
    var description: String {
        return rawValue.description
    }
}

现在,您可以获取原始值为Int或自定义类型的枚举的自动描述(只要该类型具有自己的描述)。

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...