swift Codable 中的 GMSPath 不符合协议 swift
GMSPath in swift Codable does not conform to protocol swift
我创建了一个模型并使用了 codable。我目前正在使用 GMSPath 获取路径,但是在添加到模型 class 时,我收到错误 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)
}
}
我创建了一个模型并使用了 codable。我目前正在使用 GMSPath 获取路径,但是在添加到模型 class 时,我收到错误 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)
}
}