繁体   English   中英

swift 中的 GMSPath 可编码不符合协议 swift

[英]GMSPath in swift Codable does not conform to protocol swift

我创建了一个 model 并使用它进行编码。 我目前正在使用 GMSPath 来获取路径,但是在添加到 model class 时,我收到错误Type 'EstimateResponse' does not conform to protocol 'Decodable'并且Type 'EstimateResponse' does not conform to protocol 'Encodable'

下面是我的 Model

class EstimateResponse: Codable {

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

任何帮助表示赞赏

GMSPath有一个encodedPath属性(它是一个字符串),它也可以用一个编码路径初始化。 您只需要将GMSPath编码为其编码路径表示。

使用显式实现将EstimateResponseCodable一致:

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)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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