我试图解码一个json文件,并且我在那里有很多ui配置,我正在寻找一个干净的解决方案以直接将十六进制代码解析为UIColor。但是UIColor不符合Codable。
例如这个json:
var json = """
{
"color": "#ffb80c"
}
""".data(using: .utf8)!
Run Code Online (Sandbox Code Playgroud)
我希望能够做到这一点:
struct Settings: Decodable {
var color: UIColor
}
Run Code Online (Sandbox Code Playgroud)
并且即时解码时将“ hex”字符串转换为UIColor
我已经有了此函数来从String解码并返回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
}
}
Run Code Online (Sandbox Code Playgroud)
为此,我需要通过获取容器并对其进行解码来对其进行手动解码,但是由于我有很多配置,因此我的课程非常庞大,因为我需要设置所有内容:
struct Settings: Decodable {
var color: Color
enum CodingKeys: CodingKey {
case color
}
init(from decoder: Decoder) throws {
let container = try …Run Code Online (Sandbox Code Playgroud)