Swift 4 has Codable and it's awesome. But UIImage
does not conform to it by default. How can we do that?
I tried with singleValueContainer
and 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)
}
}
I get 2 errors
- 'required' initializer must be declared directly in class 'UIImage' (not in an extension)
- A non-failable initializer cannot delegate to failable initializer 'init(data:)' written with 'init?'
A workaround is to use wrapper. But are there any other ways?
sub class
ofUIImage
that confirms toCodable
and add required initializer on that. – MilepostUIImage
toCodable
? Images generally aren't good candidates for being encoded to formats such as JSON or XML. Usually it's better to encode the image separately, and then encode for example a URL in the JSON. – LindieJSONEncoder
? but it is just one implementation ofEncoder
protocol – FailsafeFoundation
. – Lindie