Search code examples
swiftdata

Description-field in a @Model


I have a @Model class like so:

@Model
final class MyModel {

    @Attribute(.unique) var id: String
    var obj1: Object1
    var obj2: Object2

    init(id: String, obj1: Object1, obj2: Object2) {
        self.id = id
        self.obj1 = obj1
        self.obj2 = obj2
    }
    
}

Object1 and Object2 are both structs like so:

struct Object1: Codable {

   var description: String
}

I've noticed that I get an immediate runtime error error when trying to use the model in my app with

.modelContainer(for: [MyModel.self])

Unable to have an Attribute named description

After some digging I came to the conclusion that the error is due to the description fields of Object1 and Object2. However I need those two structs to contain that specific field, because they represent incoming JSON data. How can I resolve that issue in the optimal way?


Solution

  • Don't know why the word description is a problem, there is not enough information from your code.

    But note, if you are getting the properties from JSON, then you can use CodingKeys to rename them. For example:

    struct Object1: Codable {
        var info: String
        // ...
        enum CodingKeys: String, CodingKey {
            case info = "description"  // <--- here, description in the JSON data
            //...
        }
    }