struct Task: Codable {
var content: String
var deadline: Date
var color: UIColor
...
}
There are warnings saying "Type 'Task' does not conform to protocol 'Decodable'" and "Type 'Task' does not conform to protocol 'Encodable'". I searched and found that this is because UIColor does not conform to Codable. But I have no idea how to fix that. So...
How to make UIColor Codable?
I solved this issue with a custom class that allowed automatic conformance to codable. This is beneficial as it prevents writing custom conformance to codable. It also makes it easier to work with UIColor and and CGColor
}
Here's a solution which I've published as a GitHub gist which will work for any color in any color space:
It's relatively easy to use:
Of course, you can also use it as any other Swift codable, like in a struct with auto-synthesized codable conformance:
This will work with
NSColor
as well.I use
UIColor
subclassThus, there is no need for each class or structure to implement the functions of the
Decodable
protocol. It seems to me that this is the most convenient way, especially when there can be many color parameters in one class or structure. You can implementEncodable
in the same way if it's necessary.If you care only about the 4 color components this is a simple solution using a wrapper struct
In this case you have to write a custom initializer to convert the 4 color components from
Color
toUIColor
and vice versa.Now you can encode and decode
UIColor