【问题标题】:Structs inside classes for global constants in SwiftSwift 中全局常量的类内部结构
【发布时间】:2016-05-24 17:04:55
【问题描述】:

我在 swift 中使用 Util 类作为助手类。除了函数之外,我还想用自定义颜色实现一些常量。

这样使用Struct是否正确?

class Util: NSObject {

struct Colors {
    static let white = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
    static let orangeCantaloupe = UIColor(red: 1, green: 204/255, blue: 102/255, alpha: 1)
    static let greyMercury = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
    static let greyMagnesium = UIColor(red: 179/255, green: 179/255, blue: 179/255, alpha: 1)

}

class func anyFunction() {

.......
 }
}

【问题讨论】:

  • 你应该创建一个辅助函数来生成UIColors,它抽象出所有那些/255s
  • Util类中的静态变量使用extension移动到UIColor

标签: swift struct global-scope


【解决方案1】:

您可以用新颜色扩展UIColor

extension UIColor {
   static let white = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
   static let orangeCantaloupe = UIColor(red: 1, green: 204/255, blue: 102/255, alpha: 1)
   static let greyMercury = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
   static let greyMagnesium = UIColor(red: 179/255, green: 179/255, blue: 179/255, alpha: 1)
}

在需要UIColor 的上下文中,可以隐含类型,因此您可以只写something.color = .orangeCantaloupe

或者,您可以将它们保存在单独的名称空间中(为了清晰而不是方便),例如 BrandColors。空枚举效果最好,因此您知道没有人会意外实例化无意义的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    相关资源
    最近更新 更多