【发布时间】:2018-02-22 04:18:31
【问题描述】:
Swift 4 有 Codable,它很棒。但是UIImage默认不符合。我们该怎么做?
我试过singleValueContainer和unkeyedContainer
extension UIImage: Codable {
// 'required' initializer must be declared directly in class 'UIImage' (not in an extension)
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let data = try container.decode(Data.self)
guard let image = UIImage(data: data) else {
throw MyError.decodingFailed
}
// A non-failable initializer cannot delegate to failable initializer 'init(data:)' written with 'init?'
self.init(data: data)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
guard let data = UIImagePNGRepresentation(self) else {
return
}
try container.encode(data)
}
}
我收到 2 个错误
- “必需”初始化程序必须直接在“UIImage”类中声明(而不是在扩展中)
- 不可失败的初始化程序不能委托给用“init?”编写的可失败初始化程序“init(data:)”
一种解决方法是使用包装器。但是还有其他方法吗?
【问题讨论】:
-
-
您究竟为什么要将
UIImage与Codable一致?图像通常不适合编码为 JSON 或 XML 等格式。通常最好单独编码图像,然后在 JSON 中编码例如 URL。 -
如果您需要将图像保存在 JSON 字符串中,只需将图像数据转换为 base64 字符串并将其保存为字符串
-
@Hamish @LeoDabus 我没有在我的问题中提到 json 或 xml。我想你建议
JSONEncoder?但这只是Encoder协议的一种实现 -
@onmyway133 我的主要问题只是问为什么你想要这个:) 其余的是基于@现在提供的当前(和常用)编码器/解码器的假设987654333@.