I'm making a drawing app and I would like to refer to my colors through use of an enum. For example, it would be cleaner and more convenient to use Colors.RedColor
instead of typing out values every time I want that red color. However, Swift's raw value enums don't seem to accept UIColor as a type. Is there a way to do this with an enum or something similar?
We had to do this because Swift doesn't allow us to have both: raw values and associated values within the same enum. A Swift enum can either have raw values or associated values. Why is that? It's because of the definition of a raw value: A raw value is something that uniquely identifies a value of a particular type.
An enum is a special type of variable that is specifically used with switch and conditionals. Swift enumeration cases don't have unique default integer values (like an array), unlike languages such as TypeScript and Objective C where the first element has a value of 0 , the second a value of 1 , and so on.
enum have a property named 'hashValue' which is its index inside the enum.
In Swift, we can also assign values to each enum case. For example, enum Size : Int { case small = 10 case medium = 12 ... } Here, we have assigned values 29 and 31 to enum cases small and medium respectively.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With