I store Strings, and have no issue. Try this function and extension, and confirm that they encode and decode your colours correctly:
func colorToHex(_ colour: Color) -> String {
guard let components: [CGFloat] = colour.cgColor?.components else { return "#FFFFFFFF" }
if(components.count == 2) {
return String(format: "#%02lX%02lX%02lX", lroundf(Float(components[0]) * 255.0), lroundf(Float(components[0]) * 255.0), lroundf(Float(components[0]) * 255.0))
}
return String(format: "#%02lX%02lX%02lX%02lX", lroundf(Float(components[0]) * 255.0), lroundf(Float(components[1]) * 255.0), lroundf(Float(components[2]) * 255.0), lroundf(Float(components[3]) * 255.0))
}
extension UIColor {
public convenience init?(fromHex: String) {
if(!fromHex.hasPrefix("#")) {
return nil;
}
let r, g, b, a: CGFloat
let start = fromHex.index(fromHex.startIndex, offsetBy: 1)
let hexColor = String(fromHex[start...])
if(hexColor.count == 8) {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if(scanner.scanHexInt64(&hexNumber)) {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
a = CGFloat(hexNumber & 0x000000ff) / 255
self.init(red: r, green: g, blue: b, alpha: a)
return
}
}
return nil;
}
}
Note, the extension is on UIColor, but it's trivial to convert to Color.