0
votes

I have this struct

struct Photo: Codable {
    var image: UIImage
    let caption: String?
    let location: CLLocationCoordinate2D?
}

private enum CodingKeys: String, CodingKey {
    case image = "image"
    case caption = "caption"
    case location = "location"
}

I get this 2 errors:

Type 'Photo' does not conform to protocol 'Decodable'

Type 'Photo' does not conform to protocol 'Encodable'

1
UIImage would have be Codable, and it is not. CLLocationCoordinate2D would have to be Codable too. Also CodingKeys would have to be an inner member of Photo. In this case they would not be needed at all. Your best bet is a custom encoding/decoding for UIImage by conversion to Data (png/jpeg) and probably to String.Sulthan

1 Answers

1
votes

'Photo' does not conform to protocol Encodable/Decodable because UIImage cannot be conformed to Codable. Also CLLocationCoordinate2D cannot be conformed to Codable. You can specify var image with Data type and then get UIImage from Data.

Something like this:

struct Photo: Codable {
    var imageData: Data
    let caption: String?
    let location: String?

    func getImage(from data: Data) -> UIImage? {
        return UIImage(data: data)
    }
}

private enum CodingKeys: String, CodingKey {
    case imageData = "image"
    case caption = "caption"
    case location = "location"
}