我使用枚举来存储像这样的字符串值:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后我像这样访问它们:
print("Dogs be like:" + Animals.descDog.s)
Run Code Online (Sandbox Code Playgroud)
我的问题是我可以像任何其他结构或对象一样扩展枚举,所以我不必将var s: String {}属性添加到每个枚举?
ric*_*ter 75
您想要为原始值为字符串的所有枚举添加属性吗?这听起来像约束协议扩展的情况!
extension RawRepresentable where RawValue == String {
var description: String {
return rawValue
}
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为具有原始值的所有枚举都自动符合RawRepresentable协议,并且所述协议具有相关类型RawValue,告诉您原始值是哪种类型.
现在你的Animals枚举会自动继承它:
print(Animals.descCat.description) // -> "I has attitude"
Run Code Online (Sandbox Code Playgroud)
请注意,字符串枚举本身已经存在CustomStringConvertible,因此它们已经有一个description属性(返回枚举大小写的名称),而你的属性不会覆盖它:
print(Animals.descCat) // -> "descCat"
Run Code Online (Sandbox Code Playgroud)
如果您希望description覆盖默认值,只需CustomStringConvertible在枚举中添加一致性声明:
private enum Animals: String, CustomStringConvertible { /*...*/ }
print(Animals.descCat) // -> "I has attitude"
Run Code Online (Sandbox Code Playgroud)
您还可以扩展此想法以涵盖其他原始值类型.例如:
extension RawRepresentable where RawValue: CustomStringConvertible {
var description: String {
return rawValue.description
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以获得原始值为Int甚至是自定义类型的枚举的自动描述(只要该类型具有description自己的类型).
| 归档时间: |
|
| 查看次数: |
21852 次 |
| 最近记录: |