Im trying to decode a json file, and i have alot of ui configurations there, and im looking for a clean solution to parse directly a hex code to UIColor. But UIColor doesnt conform to Codable.
For example this json:
var json = """
{
"color": "#ffb80c"
}
""".data(using: .utf8)!
and i want to be able to do this:
struct Settings: Decodable {
var color: UIColor
}
and while im decoding convert the "hex" string into a UIColor
I already have this function to decode from a String and return a UIColor:
public extension KeyedDecodingContainer {
public func decode(_ type: UIColor.Type, forKey key: Key) throws -> UIColor {
let colorHexString = try self.decode(String.self, forKey: key)
let color = UIColor(hexString: colorHexString)
return color
}
}
For this to work i need to decode it manually by getting the container and decode it, but since i have alot of configurations my class will be huge because i need to set everything:
struct Settings: Decodable {
var color: Color
enum CodingKeys: CodingKey {
case color
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
color = try container.decode(UIColor.self, forKey: .color)
}
}
In the end im looking for a much cleaner way to do this. The ideal way is to turn UIColor codable (but i think i cant do that)
Thanks in advance