我使用枚举来存储这样的字符串值:
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)
我的问题是我能否像扩展任何其他结构或对象一样扩展枚举,这样我就不必将 var s: String {}
属性添加到每个枚举?
最佳答案
您想为原始值为字符串的所有枚举添加一个属性吗?这听起来像是受限协议(protocol)扩展的案例!
extension RawRepresentable where RawValue == String {
var description: String {
return rawValue
}
}
这是有效的,因为所有具有原始值的枚举自动符合 RawRepresentable
协议(protocol),并且所述协议(protocol)具有关联类型 RawValue
告诉您原始值是哪种类型.
现在您的 Animals
枚举将自动继承它:
print(Animals.descCat.description) // -> "I has attitude"
请注意,字符串枚举本身已经是 CustomStringConvertible
,因此它们已经具有 description
属性(返回枚举案例的名称),而您的不会覆盖它:
print(Animals.descCat) // -> "descCat"
如果您希望您的description
覆盖默认值,只需添加CustomStringConvertible
声明以符合您的枚举:
private enum Animals: String, CustomStringConvertible { /*...*/ }
print(Animals.descCat) // -> "I has attitude"
您还可以扩展此想法以涵盖其他原始值类型。例如:
extension RawRepresentable where RawValue: CustomStringConvertible {
var description: String {
return rawValue.description
}
}
现在,您可以获得原始值为 Int
或自定义类型(只要该类型有自己的描述
)的枚举的自动描述。
关于swift - 你能扩展一个枚举吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33444932/