使用Codable(Swift)从Json文件解析UIColor [英] Parse UIColor from Json file with Codable (Swift)
问题描述
我正在尝试解码json文件,并且我在那里有很多ui配置,我正在寻找一种干净的解决方案以直接将十六进制代码解析为UIColor。但是UIColor不符合Codable。
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.
例如,此json:
var json = """
{
"color": "#ffb80c"
}
""".data(using: .utf8)!
而我希望能够做到这一点:
and i want to be able to do this:
struct Settings: Decodable {
var color: UIColor
}
,而即时解码将十六进制字符串转换为UIColor
and while im decoding convert the "hex" string into a UIColor
我已经具有此功能,可以从字符串中解码并返回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)
}
}
最终im寻找一种更清洁的方法来执行此操作。理想的方法是将UIColor设置为可编码(但我认为我不能做到这一点)
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)
预先感谢
推荐答案
我要解决此问题的方法是引入一种新的 Color
类型,该类型符合 Decodable
协议并包装单个 UIColor
属性:
What I did to solve this problem is to introduce a new Color
type that conforms to the Decodable
protocol and wraps a single UIColor
property:
struct Color : Decodable {
let value: UIColor
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
self.value = try UIColor(rgba_throws: string) // From https://github.com/yeahdongcn/UIColor-Hex-Swift
}
}
然后您将使用它:
cell.textLabel?.textColor = settings.color.value
仅适用于UIColor,如果您希望使其适用于不符合Decoda的任何类型作为一种协议,John Sundell在在Swift中自定义可编码类型中描述了一种通用方法。
That's for UIColor only, if you want to make it work for any type that doesn't conform to the Decodable protocol, John Sundell describes a generic approach in Customizing Codable types in Swift.
这篇关于使用Codable(Swift)从Json文件解析UIColor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!