Persist SwiftUI Color

The new ColorPicker is nice, but it only returns SwiftUI Color. It's great that it changes the binding variable, but how can it be persisted to something like UserDefaults or Core Data? It can't be converted to Data, RGB, hex, or UIColor. So ,how can it be persisted?
If anybody stumbles upon this, this is what I ended up doing for my app. In CoreData model, I declared an attribute ColorData of type Binary Data and in the model extension, I wrote a property like this

Code Block Swift
#if os(iOS)
import UIKit
#endif
#if os(macOS)
import Foundation
#endif
extension Model {
private struct ColorData: Codable {
var r: Double
var g: Double
var b: Double
var a: Double
}
var color: Color {
get {
guard let data = colorData, let decoded = try? JSONDecoder().decode(ColorData.self, from: data) else { return Color(assetName: .accent) }
return Color(.sRGB, red: decoded.r, green: decoded.g, blue: decoded.b, opacity: decoded.a)
}
set(newColor) {
#if os(iOS)
let nativeColor = UIColor(newColor)
#elseif os(macOS)
let nativeColor = NSColor(newColor)
#endif
var (r, g, b, a) = (CGFloat.zero, CGFloat.zero, CGFloat.zero, CGFloat.zero)
nativeColor.getRed(&r, green: &g, blue: &b, alpha: &a)
if let encoded = try? JSONEncoder().encode(ColorData(r: Double(r), g: Double(g), b: Double(b), a: Double(a))) {
colorData = encoded
}
}
}
}


Having this ready, you can simply read and write SwiftUI Color to the model object
Code Block Swift
let obj = Model(context: context)
obj.color = .blue // This will call the setter which will take care of converting Color to Data to store in CoreData


This may not be the best solution for all cases but it works for me so I thought I would share.

Persist SwiftUI Color
 
 
Q