嗯,老实说,我不喜欢在访问 enum
值时调用 rawValue
。
我几乎一直都这样使用 enum
,我认为调用 .rawValue
会降低我的代码的“可读性”:
enum FontSize: CGFloat {
case Small = 12
case Normal = 15
case Large = 18
}
enum Example: String {
case First = "First"
case Second = "Second"
}
因此,我正在尝试为“覆盖”.rawValue
的enum
定义一个通用运算符。
我可以非一般地做到这一点。
postfix operator .. { }
postfix func .. (lhs: Example) -> String {
return lhs.rawValue
}
postfix func .. (lhs: FontSize) -> CGFloat {
return lhs.rawValue
}
但是,我很懒,想要一个通用的解决方案。写一个,全部工作。
有人可以帮我吗?谢谢。
更新:对这个问题感兴趣的人,如果你想增加/减少enum
的函数,比如上面的FontSize
。使用这些:
postfix func ++ <T: RawRepresentable, V: FloatingPointType>(lhs: T) -> V {
return (lhs.rawValue as! V) + 1
}
postfix func -- <T: RawRepresentable, V: FloatingPointType>(lhs: T) -> V {
return (lhs.rawValue as! V) - 1
}
postfix func ++ <T: RawRepresentable, V: IntegerType>(lhs: T) -> V {
return (lhs.rawValue as! V) + 1
}
postfix func -- <T: RawRepresentable, V: IntegerType>(lhs: T) -> V {
return (lhs.rawValue as! V) - 1
}
最佳答案
黑哥,你真懒! ;-)
postfix operator .. { }
postfix func ..<T: RawRepresentable> (lhs: T) -> T.RawValue {
return lhs.rawValue
}
有一个协议(protocol):-)
无论如何要注意不要引入太多深奥的自定义运算符;-)
关于ios - 用自定义运算符替换枚举的 rawValue 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29181242/