微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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或自定义类型的枚举的自动描述(只要该类型具有自己的描述)。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐