简体   繁体   中英

GMSPath in swift Codable does not conform to protocol swift

I created a model and used codable with it. I am currently using GMSPath to get path, but on adding to the model class, I get the error Type 'EstimateResponse' does not conform to protocol 'Decodable' and Type 'EstimateResponse' does not conform to protocol 'Encodable'

below is my Model

class EstimateResponse: Codable {

    var path: GMSPath? // Set by Google directions API call
    var destination: String?
    var distance: String?
}

any help is appreciated

GMSPath has an encodedPath property (which is a string), and it can also be initialised with an encoded path. You just need to encode your GMSPath to its encoded path representation.

Conform EstimateResponse to Codable with explicit implementations:

class EstimateResponse : Codable {
    var path: GMSPath?
    var destination: String?
    var distance: String?

    enum CodingKeys: CodingKey {
        case path, destination, distance
    }
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let encodedPath = try container.decode(String.self, forKey: .path)
        path = GMSPath(fromEncodedPath: encodedPath)
        destination = try container.decode(String.self, forKey: .destination)
        distance = try container.decode(String.self, forKey: .distance)
    }

    func encode(to encoder: Encoder) throws {
        var container = try encoder.container(keyedBy: CodingKeys.self)
        try container.encode(path?.encodedPath(), forKey: .path)
        try container.encode(destination, forKey: .destination)
        try container.encode(distance, forKey: .distance)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM