swift Codable 中的 GMSPath 不符合 swift 协议



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

下面是我的模型

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

任何帮助不胜感激

GMSPath有一个encodedPath属性(它是一个字符串(,也可以使用编码路径进行初始化。您只需要将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)
}
}

相关内容

  • 没有找到相关文章

最新更新