Enum & custom type from primitive JSON type

Add custom encode/decode for UIImage in KeyedEncodingContainer :And use this with explicit encode and decode.struct ModelUsingKeyedEncodingContainer: Codable { let name: String let image: UIImage enum CodingKeys: String, CodingKey { case name case image } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) name = try container.decode(String.self, forKey: .name) image = try container.decode(UIImage.self, forKey: .image) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(image, forKey: .image) }}These 2 approaches should suffice for most of your use cases.. More details

Leave a Reply