It seems that SwiftData and Codable model properties are seriously broken (at least as of Xcode 15.0 beta 3). I'm getting the same error shown in the above question for any model property whose type is anything marked as Codable. I am finding that in many cases the custom encode method is never called when storing a value in an instance of the model. And when reading the property, the init(from:) isn't encoded as expected.
I was able to get things to work for CLLocationCoordinate2D with the following implementation:
extension CLLocationCoordinate2D: Codable {
// These exact case values must be used to decode a location
enum CodingKeys: CodingKey {
case latitude
case longitude
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let lat = try container.decode(CLLocationDegrees.self, forKey: .latitude)
let lon = try container.decode(CLLocationDegrees.self, forKey: .longitude)
self = CLLocationCoordinate2D(latitude: lat, longitude: lon)
}
// Never called by SwiftData
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.latitude, forKey: .latitude)
try container.encode(self.longitude, forKey: .longitude)
}
}
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags: