项目中 SwiftData 要将 CLLocationCoordinate2D 作为数组存储对象,但报错:
1
| Referencing instance method 'setValue(forKey:to:)' on 'Array' requires that 'CLLocationCoordinate2D' conform to 'PersistentModel'
|
需要:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| enum CodingKeys: String, CodingKey { case latitude case longitude }
extension CLLocationCoordinate2D: Decodable { public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.init() latitude = try values.decode(Double.self, forKey: .latitude) longitude = try values.decode(Double.self, forKey: .longitude) } }
extension CLLocationCoordinate2D: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(latitude, forKey: .latitude) try container.encode(longitude, forKey: .longitude) } }
|
从这里也可以看出,使用 SwiftData 存储的对象可以直接使用 ==
来判断两者是否为同一对象(SwiftData 可以使用等于(==)和非等于(!=)运算符比较等于类型的实例)。
例如在获得数组元素 index 时:
1 2 3 4 5
| if let index = items.firstIndex(where: { $0.id == item.id })
if let index = items.firstIndex(where: { $0 == item })
|
参考:
- How to use CLLocationCoordinate2D and Color data types in Swift Data?
- CLLocationCoordinate2d does not conform to ‘PersistentModel’ SwiftData
- Swift 自定义结构体和类应该遵循的通用协议