在Swift中为全局常量的类内部构造

时间:2016-05-24 17:04:56

标签: swift struct global-scope

我在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() {

.......
 }
}

2 个答案:

答案 0 :(得分: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。空枚举效果最好,所以您知道没有人会意外地实例化一个毫无意义的对象。

答案 1 :(得分:-1)

这是枚举的工作。

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