Background: I’ve downloaded Bus Service information from the internet and decoded it into JSON using a struct that comes with CodingKeys. This works as expected
struct Service: Codable {
var serviceNo: String
//Other properties
enum CodingKeys: String, CodingKey {
case serviceNo = "serviceNo"
//other properties from the JSON that require decoding
}
}
I then have a @Model class to store a combination of the service along with bus stop information. Simplified, it looks like this:
@Model
class FrequentService {
var service: Service
var stop: BusStop
init(){ .. }
}
Im using modelContainer and modelContext to fetch an array of FrequentService and displaying it in my UI using the query property
@Query var frequentServices: [FrequentService]
When I do this I get an error from Core Data. It says CoreData: error: “Row (pk = 1) for entity ‘FrequentService’ is missing mandatory text data for property ‘serviceNo’
What I’ve tried: Upon testing I’ve realised that an error occurs upon insert of a new FrequentService into the context. At that point I print out the ‘serviceNo’ information from the service property and can tell that it’s not missing. It does have a value. I’ve managed to isolate the error to the fact that enum CodingKeys is present in the Service struct. Without that, SwiftData works just fine. It might be the case that the ‘serviceNo’ inside the enum is causing the problem.
Challenge: I need the CodingKeys within Service to encode and decode the JSON information. But it seems I also need to remove it to use SwiftData. The only solution I’ve thought of is to create a duplicate Service struct under a different name without the enum, map the values to this struct and store this new struct within the FrequentService object. But that seems really wasteful with the duplicate structs that are nearly identical.
Question: Is my only option to create the duplicate struct? Or is there a way to save the Service struct as is with the enum CodingKey included?
Thanks!




