NSColor from/to HTML colors

Here’s a nice little extension I wrote to create NSColors given an html string and vice versa getting an html string from an existing NSColor. Hope it’s useful.

extension NSColor {
    
    public convenience init?(htmlString: String) {
        let hexColor = htmlString.replacingOccurrences(of: "#", with: "")
        
        let scanner = Scanner(string: hexColor)
        var hexNumber: UInt64 = 0
        
        if scanner.scanHexInt64(&hexNumber) {
            let red = CGFloat(((hexNumber & 0xFF0000) >> 16)) / 255.0
            let green = CGFloat(((hexNumber & 0x00FF00) >> 8)) / 255.0
            let blue = CGFloat(((hexNumber & 0x0000FF) >> 0)) / 255.0
            self.init(red: red, green: green, blue: blue, alpha: 1.0)
            return
        }

        return nil
    }
    
    func toHTMLString() -> String {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        self.getRed(&r, green: &g, blue: &b, alpha: &a)
        return String(
            format: "#%02X%02X%02X",
            Int(r * 0xff),
            Int(g * 0xff),
            Int(b * 0xff)
        )
    }
}