我创建了一个模型并使用了可编码的。我目前正在使用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?
}任何帮助都是非常感谢的。
发布于 2019-09-19 15:38:44
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)
}
}https://stackoverflow.com/questions/58014280
复制相似问题