Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a Swift enum with UIColor value?

Tags:

enums

swift

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?

like image 335
A Tyshka Avatar asked Aug 24 '16 01:08

A Tyshka


People also ask

Why Swift enums with associated values Cannot have a raw value?

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.

Can enums have variables Swift?

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.

What is hash value in enum Swift?

enum have a property named 'hashValue' which is its index inside the enum.

How do I enum in Swift?

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.


2 Answers

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.

like image 176
FranMowinckel Avatar answered Sep 19 '22 19:09

FranMowinckel


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 
like image 20
Code Different Avatar answered Sep 21 '22 19:09

Code Different