我将尝试翻译一个JSON文件,其中包含许多UI配置,并寻找一种干净的解决方案,以直接将十六进制代码解析为UIColor。但是UIColor不符合Codable。
例如,这个JSON:
var json = """
{
"color": "#ffb80c"
}
""".data(using: .utf8)!
我希望您能够实现以下功能:
我想要能够做到这一点:
struct Settings: Decodable {
var color: UIColor
}
在解码的同时将“hex”字符串转换为UIColor。
我已经有了这个从字符串解码并返回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
}
}
为了使其正常工作,我需要手动解码容器并对其进行解码,但由于我有很多配置,所以我的类将会非常庞大,因为我需要设置所有内容。
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)
}
}
最终,我希望找到一种更加简洁的方法来实现这个。理想的方式是将UIColor编码(但我认为我做不到)。
提前感谢。