Swift中含GMSPath的EstimateResponse模型不遵循Codable协议问题求助
嗨,这个问题我之前也碰到过!核心原因很简单——GMSPath并没有实现Codable协议,而你的EstimateResponse默认依赖编译器自动合成Codable的实现,编译器不知道怎么处理GMSPath类型的属性,所以就抛出了不遵守协议的错误。给你两个实用的解决方案:
方案一:将path排除在Codable序列化范围外
如果你的path属性只是通过Google Directions API调用后本地赋值,不需要参与编码(比如存到UserDefaults、或者通过网络传输),那最简单的办法就是自定义CodingKeys枚举,只包含需要序列化的属性:
class EstimateResponse: Codable { var path: GMSPath? // 这个属性不参与Codable流程 var destination: String? var distance: String? // 自定义CodingKeys,仅声明需要编码解码的属性 enum CodingKeys: String, CodingKey { case destination, distance } }
这样编译器就会基于你定义的CodingKeys自动合成符合要求的Codable实现,完全忽略path属性。
方案二:让GMSPath支持Codable
如果你的业务需要把path也一起序列化(比如持久化到本地或者传给其他模块),那可以给GMSPath写一个Codable扩展,利用它自带的路径字符串转换能力来实现编码解码:
extension GMSPath: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.encodedPath()) } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let encodedPath = try container.decode(String.self) guard let path = GMSPath(fromEncodedPath: encodedPath) else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid encoded path string") } self = path } }
写完这个扩展后,你的原EstimateResponse模型不需要做任何修改,就能正常遵守Codable协议了——编译器会自动处理包括path在内的所有属性。
内容的提问来源于stack exchange,提问作者King
相关产品推荐
相关产品推荐

