ios - 用自定义运算符替换枚举的 rawValue 属性

标签 ios swift

嗯,老实说,我不喜欢在访问 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"
}

因此,我正在尝试为“覆盖”.rawValueenum 定义一个通用运算符。
我可以非一般地做到这一点。

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
}

Gist for future reference here

最佳答案

黑哥,你真懒! ;-)

postfix operator .. { }

postfix func ..<T: RawRepresentable> (lhs: T) -> T.RawValue {
    return lhs.rawValue
}

有一个协议(protocol):-)

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

关于ios - 用自定义运算符替换枚举的 rawValue 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29181242/

相关文章:

ios - 我的通话错误 : Incorrect Argument Label In Call (have 'key:' , 预期为 'coder:' )

ios - Swift:多功能问题

json - Swift json 解析数组

swift - 你如何在不使用 UIKit 的情况下处理对 SKSpriteNode 的点击

ios - 在 ios 中将 Storyboard从一个应用程序复制到另一个应用程序的最佳方法是什么?

javascript - 如何将 json 从 JavaScript 传递到 iPad native 应用程序?

swift - 如何在多个 UITableView 中保留导航栏

ios - 删除/停止 dispatch_async iOS

ios - 如何运行导致框架运行时错误的 iOS 应用程序 "code signature invalid"

ios - scrollview 快速滚动时如何滚动 collectionView?