Skip to content

Instantly share code, notes, and snippets.

@onmyway133
Created June 15, 2018 08:56
Show Gist options
  • Save onmyway133/1e9f2128972baa6d1ad1c3a9d49314ce to your computer and use it in GitHub Desktop.
Save onmyway133/1e9f2128972baa6d1ad1c3a9d49314ce to your computer and use it in GitHub Desktop.
a.swift
// WARNING: This does not compile
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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment