用自定义运算符替换enum的rawValue属性

Pha*_*oan 1 ios swift

嗯,说实话,我不喜欢rawValue在访问enum价值时打电话.
enum几乎一直都这样使用,我认为调用.rawValue使我的代码不那么"可读":

enum FontSize: CGFloat {
    case Small = 12
    case Normal = 15
    case Large = 18
}
enum Example: String {
    case First = "First"
    case Second = "Second"
}
Run Code Online (Sandbox Code Playgroud)

所以,我正在尝试为enum"覆盖" 定义一个泛型运算符.rawValue.
我可以非一般地做.

postfix operator .. { }

postfix func .. (lhs: Example) -> String {
    return lhs.rawValue
}

postfix func .. (lhs: FontSize) -> CGFloat {
    return lhs.rawValue
}
Run Code Online (Sandbox Code Playgroud)

但是,我很懒,我想要一个通用的解决方案.写一个,全部工作.

有人可以帮我吗?谢谢.


更新:如果您希望增加/减少功能谁感兴趣这个问题,人们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
}
Run Code Online (Sandbox Code Playgroud)

这里要点以供将来参考

Mat*_*mbo 5

嘿嘿,你真的很懒!;-)

postfix operator .. { }

postfix func ..<T: RawRepresentable> (lhs: T) -> T.RawValue {
    return lhs.rawValue
}
Run Code Online (Sandbox Code Playgroud)

有一个协议:-)

无论如何要注意不要引入太多深奥的自定义运算符;-)