For various reasons you may want to convert the Color
type to a String
. And, below is a relatively cleaner way to do it.
import SwiftUI
extension Color: RawRepresentable {
public init(rawValue: String) {
guard let data = Data(base64Encoded: rawValue) else {
self = .gray
return
}
do {
let color = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSColor.self, from: data) ?? .gray
self = Color(color)
} catch {
self = .gray
}
}
public var rawValue: String {
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: NSColor(self), requiringSecureCoding: false) as Data
return data.base64EncodedString()
} catch {
return ""
}
}
}
You can use it like:
var rawColor: String = Color.blue.rawValue
var someColor: Color = Color(rawValue: rawColor)