【发布时间】:2019-05-06 05:48:56
【问题描述】:
我正在尝试解码一个 json 文件,我在那里有很多 ui 配置,我正在寻找一个干净的解决方案来直接将十六进制代码解析为 UIColor。但是 UIColor 不符合 Codable。
例如这个json:
var json = """
{
"color": "#ffb80c"
}
""".data(using: .utf8)!
我希望能够做到这一点:
struct Settings: Decodable {
var color: UIColor
}
在解码时将“十六进制”字符串转换为 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 可编码(但我认为我不能这样做)
提前致谢
【问题讨论】:
标签: ios json iphone swift codable