Search code examples
swifthexuicoloruint

Convert hex color as string to Uint


Ive been searching this for ages and cant find a solution that works or that i understand.

I have a string in database "0x6c8c93" that i want to convert into a Uint so i can convert it to a colour.

Below is the function I've been using to convert Uint to colour previously. and I've just been passing it the hex value from colour charts in this format 0x6c8c93. However now i need to pull some values from the DB so I've got to go with string.

class func UIColorFromHEX(hexValue: UInt) -> UIColor {
    return UIColor(
        red: CGFloat((hexValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((hexValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(hexValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
}

Thanks for help.


Solution

  • Here is one way to do it. Use string.suffix(6) to keep the last 6 characters of the string, and then use the UInt initializer UInt(_:radix:) to convert the hexString to a UInt?. If the conversion succeeds it will return an Optional UInt that is then unwrapped by if let and assigned to hexValue:

    let string = "0x6c8c93"
    
    if let hexValue = UInt(string.suffix(6), radix: 16) {
        // create the color from hexValue
    }