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:)”
一种解决方法是使用包装器。但是还有其他方法吗?