[英]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
編碼為其編碼路徑表示。
使用顯式實現將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)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.