首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >快速编码中的GMSPath不符合协议conform

快速编码中的GMSPath不符合协议conform
EN

Stack Overflow用户
提问于 2019-09-19 15:21:12
回答 1查看 206关注 0票数 0

我创建了一个模型并使用了可编码的。我目前正在使用GMSPath获取路径,但是在添加到模型类时,我会得到错误Type 'EstimateResponse' does not conform to protocol 'Decodable'Type 'EstimateResponse' does not conform to protocol 'Encodable'

下面是我的模型

代码语言:javascript
复制
class EstimateResponse: Codable {

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

任何帮助都是非常感谢的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-19 15:38:44

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

使用显式实现使EstimateResponseCodable保持一致:

代码语言:javascript
复制
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)
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58014280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档