使 UIColor 可编码 [英] Make UIColor Codable
问题描述
struct Task: Codable {
var content: String
var deadline: Date
var color: UIColor
...
}
有警告说类型‘任务’不符合协议‘可解码’"和类型‘任务’不符合协议‘可编码’".我搜索了一下,发现这是因为 UIColor 不符合 Codable.但我不知道如何解决这个问题.所以...
There are warnings saying "Type 'Task' does not conform to protocol 'Decodable'" and "Type 'Task' does not conform to protocol 'Encodable'". I searched and found that this is because UIColor does not conform to Codable. But I have no idea how to fix that. So...
如何使 UIColor 可编码?
How to make UIColor Codable?
推荐答案
如果您只关心 4 种颜色组件,这是一个使用包装结构的简单解决方案
If you care only about the 4 color components this is a simple solution using a wrapper struct
struct Color : Codable {
var red : CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0
var uiColor : UIColor {
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
init(uiColor : UIColor) {
uiColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
}
}
在这种情况下,您必须编写一个自定义初始化程序来将 4 个颜色组件从 Color
转换为 UIColor
,反之亦然.
In this case you have to write a custom initializer to convert the 4 color components from Color
to UIColor
and vice versa.
struct Task: Codable {
private enum CodingKeys: String, CodingKey { case content, deadline, color }
var content: String
var deadline: Date
var color : UIColor
init(content: String, deadline: Date, color : UIColor) {
self.content = content
self.deadline = deadline
self.color = color
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
content = try container.decode(String.self, forKey: .content)
deadline = try container.decode(Date.self, forKey: .deadline)
color = try container.decode(Color.self, forKey: .color).uiColor
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(content, forKey: .content)
try container.encode(deadline, forKey: .deadline)
try container.encode(Color(uiColor: color), forKey: .color)
}
}
现在你可以编码和解码UIColor
let task = Task(content: "Foo", deadline: Date(), color: .orange)
do {
let data = try JSONEncoder().encode(task)
print(String(data: data, encoding: .utf8)!)
let newTask = try JSONDecoder().decode(Task.self, from: data)
print(newTask)
} catch { print(error) }
这篇关于使 UIColor 可编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!