make a function that converts a hex code to uicolor in swift

main.swift
func hexToUIColor(hex: String) -> UIColor? {
    var formattedHex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
    if formattedHex.count == 6 {
        formattedHex = "FF" + formattedHex
    }
    var rgbValue: UInt64 = 0
    Scanner(string: formattedHex).scanHexInt64(&rgbValue)
    let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
    let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0
    let blue = CGFloat(rgbValue & 0x0000FF) / 255.0
    let alpha = CGFloat((rgbValue & 0xFF000000) >> 24) / 255.0
    return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
606 chars
14 lines

This function takes a hex string and returns a UIColor object. The hex code may be in the format of either "RRGGBB" or "#RRGGBB". If the hex code does not contain an alpha value, one is assumed to be FF (fully opaque). If the conversion fails, nil is returned.

gistlibby LogSnag