Using SwiftData
, I have a model that uses an enum as a property and a custom Codable type
import SwiftData
import CoreLocation
// MARK: - Main Model
@Model
class Cache {
var size: CacheSize?
var coordinates: CLLocationCoordinate2D
}
// MARK: - CacheSize Enum
enum CacheSize: CaseIterable, Codable {
case nano
case micro
case small
case regular
case large
case veryLarge
case notChosen
case virtual
case other
}
// MARK: - Codable for CLLocationCoordinate2D
extension CLLocationCoordinate2D: Codable {
enum CodingKeys: String, CodingKey {
case lat, lng
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.latitude, forKey: .lat)
try container.encode(self.longitude, forKey: .lng)
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let latitude = try container.decode(CLLocationDegrees.self, forKey: .lat)
let longitude = try container.decode(CLLocationDegrees.self, forKey: .lng)
self.init(latitude: latitude, longitude: longitude)
}
}
When I fetch the object from the ModelContext
and try to access the property corresponding to this enum, I have a fatal error raised in BackingData.swift:
SwiftData/BackingData.swift:197: Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(iGeo.CacheSize, Swift.DecodingError.Context(codingPath: [], debugDescription: "Invalid number of keys found, expected one.", underlyingError: nil))
When I try to read the CLLocationCoordinates2D
property, I have also a crash in the Decodable
init(from decoder: Decoder
implementation when trying to read the first value from the container.
Did I miss something here or did something wrong?