Toto
Toto

Reputation: 613

Swift - How to conform this struct to Codable?

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'

Upvotes: 0

Views: 3058

Answers (1)

Rodion Kuskov
Rodion Kuskov

Reputation: 156

'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"
}

Upvotes: 1

Related Questions