How to have Codable Color?

The struct C correctly encode UIColor
Code Block
...
let c = C()
let j = c.json
...
struct C: Encodable
{
var mycolor: UIColor = .red
enum CodingKeys: String, CodingKey
{
case color
}
func encode(to encoder: Encoder) throws
{
var container = encoder.container(keyedBy: CodingKeys.self)
let colorData = try NSKeyedArchiver.archivedData(withRootObject: mycolor, requiringSecureCoding: false)
try container.encode(colorData, forKey: .color)
}
var json: Data? {try? JSONEncoder().encode(self)}
}

but it's impossible, to me, the encode Color.
Code Block
var mycolor: Color = Color(.systemRed)

I found the class UIColor is declared conforming to NSSecureCoding, but struct Color isn't and and extension to Codable isn't allowed outside of the type declaring file.

Is there a way to circumvent this limitation?
Answered by Luca_65 in 629845022
I found by myself that is possible since on iOS 14.
Code Block
func encode(to encoder: Encoder) throws
{
var container = encoder.container(keyedBy: CodingKeys.self)
if #available(iOS 14.0, *)
{
let convertedColor = UIColor(mycolor)
let colorData = try NSKeyedArchiver.archivedData(withRootObject: convertedColor, requiringSecureCoding: false)
try container.encode(colorData, forKey: .color)
} else
{
// Fallback on earlier versions
}
}

Accepted Answer
I found by myself that is possible since on iOS 14.
Code Block
func encode(to encoder: Encoder) throws
{
var container = encoder.container(keyedBy: CodingKeys.self)
if #available(iOS 14.0, *)
{
let convertedColor = UIColor(mycolor)
let colorData = try NSKeyedArchiver.archivedData(withRootObject: convertedColor, requiringSecureCoding: false)
try container.encode(colorData, forKey: .color)
} else
{
// Fallback on earlier versions
}
}

How to have Codable Color?
 
 
Q