Search code examples
iosswiftuicolor

Swift - create array of custom colors


Is there a way to create an array of custom colors? I know I can create custom colors in class UIColors but in my case I need an array of my custom colors.

I would like to achieve something like this:

let listColors: [UIColor] = [
    let color1 = UIColor(displayP3Red: 1, green: 1, blue: 1, alpha: 1),
    let color2 = UIColor(displayP3Red: 2, green: 2, blue: 2, alpha: 1),
    let color3 = UIColor(displayP3Red: 3, green: 3, blue: 3, alpha: 1),
]

Solution

  • You don't need a subclass to create an array do

    let listColors = [  
        UIColor(displayP3Red: 1, green: 1, blue: 1, alpha: 1),
        UIColor(displayP3Red: 2, green: 2, blue: 2, alpha: 1),
        UIColor(displayP3Red: 3, green: 3, blue: 3, alpha: 1)
    ]
    

    access

    listColors[index]
    

    or

    class Colors {
    
       static let color1 = UIColor(displayP3Red: 1, green: 1, blue: 1, alpha: 1)
       static let color2 = UIColor(displayP3Red: 2, green: 2, blue: 2, alpha: 1) 
       static let color3 = UIColor(displayP3Red: 3, green: 3, blue: 3, alpha: 1)
    
    }
    

    access

    Colors.color1
    

    or as global

    let color1 = UIColor(displayP3Red: 1, green: 1, blue: 1, alpha: 1)
    let color2 = UIColor(displayP3Red: 2, green: 2, blue: 2, alpha: 1) 
    let color3 = UIColor(displayP3Red: 3, green: 3, blue: 3, alpha: 1)
    

    access

    color1
    

    When you create a color divide by 255

    UIColor(displayP3Red: 2/255.0, green: 2/255.0, blue: 2/255.0, alpha: 1)