how to check if Color exists in asset catalog

110 Views Asked by At

I want to take a string and see if there's a matching color in my bundles asset catalog. If it exists the set a variable to that color and if not set to another.

e.g

let matchedColor = Color(string) ?? Color.red

however as Color(string) is not an optional I can't use nil coalescing operator.

2

There are 2 best solutions below

0
MatBuompy On

You could use something like this:

Color(uiColor: UIColor(named: "MyColor") ?? UIColor.blue)    

Which is a short for:

if let color = UIColor(named: "MyColor") {
    Color(uiColor: color)
} else {
    /// Your other color here
    Color.blue
}
0
workingdog support Ukraine On

You could try this approach using UIImage to check if the named asset is in the Assets folder:

 func isInAssets(_ name: String) -> Bool {
     UIImage(named: name) != nil ? true : false
 }