ios - swift Codable 中的 GMSPath 不符合 swift 协议(protocol)

标签 ios swift google-maps gmsplace

我创建了一个模型并使用它进行编码。我目前正在使用 GMSPath 来获取路径,但在添加到模型类时,出现错误 Type 'EstimateResponse' does not follow protocol 'Decodable'Type 'EstimateResponse' does not符合协议(protocol)“可编码”

下面是我的模型

class EstimateResponse: Codable {

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

感谢任何帮助

最佳答案

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

通过显式实现使 EstimateResponse 符合 Codable:

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

关于ios - swift Codable 中的 GMSPath 不符合 swift 协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58014280/

相关文章:

ios - 在定义的同一 IBAction 中使用未解析的标识符

ios - 递归 UITableViewCell 按钮 Action

javascript - jquery 每个如果值存在则追加到前一个值

android - Google Maps Android v1 API 已弃用 - 获取用于开发的 API key

ios - Collection View Controller 单元格间距

ios - 批量获取iOS图片

ios - TAniIndicator 在执行操作时没有动画。

swift - 当我从另一个 View 返回后, View 框架改变了它的位置[swift]

swift - 如何为泛型类型添加扩展?

android - 将 getMap 替换为 getMapAsync