How can I make a Swift enum with UIColor value?

I do it like this (basically using a struct as a namespace):

extension UIColor {
  struct MyTheme {
    static var firstColor: UIColor  { return UIColor(red: 1, green: 0, blue: 0, alpha: 1) }
    static var secondColor: UIColor { return UIColor(red: 0, green: 1, blue: 0, alpha: 1) }
  }
}

And you use it like:

UIColor.MyTheme.firstColor

So you can have a red color inside your custom theme.


If your color isn't one of those defined by UIColor's convenience method, you can add an extension to UIColor:

extension UIColor {
    static var firstColor: UIColor  { return UIColor(red: 1, green: 0, blue: 0, alpha: 1) }
    static var secondColor: UIColor { return UIColor(red: 0, green: 1, blue: 0, alpha: 1) }
}

// Usage
let myColor = UIColor.firstColor

Tags:

Enums

Swift