Solution: Minimize your own wrapper class corresponding to Codable.
One solution, since there are no extensions for UIImage , is to wrap the image in a new native class. Otherwise, your attempt is mostly direct. I saw that this was perfectly done in the Hyper Interactive caching environment, which is called, well, Cache .
Although you need to visit the library to delve deeper into dependencies, you can get an idea of ββtheir ImageWrapper class, which is built for use as follows:
let wrapper = ImageWrapper(image: starIconImage) try? theCache.setObject(wrapper, forKey: "star") let iconWrapper = try? theCache.object(ofType: ImageWrapper.self, forKey: "star") let icon = iconWrapper.image
Here is their shell class:
// Swift 4.0 public struct ImageWrapper: Codable { public let image: Image public enum CodingKeys: String, CodingKey { case image } // Image is a standard UI/NSImage conditional typealias public init(image: Image) { self.image = image } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let data = try container.decode(Data.self, forKey: CodingKeys.image) guard let image = Image(data: data) else { throw StorageError.decodingFailed } self.image = image } // cache_toData() wraps UIImagePNG/JPEGRepresentation around some conditional logic with some whipped cream and sprinkles. public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) guard let data = image.cache_toData() else { throw StorageError.encodingFailed } try container.encode(data, forKey: CodingKeys.image) } }
I would love to hear what you end up using.
UPDATE: it turns out that the OP wrote the code I was referring to (Swift 4.0 update for Cache) to solve this problem. Of course, the code deserves to be here, but I will also leave my words unedited for the dramatic irony of it all. :)
source share