Search code examples
iosswiftcore-data

Core Data custom struct array


I created a custom struct named Answer:

struct Answer {
    var isCorrect : Int
    var time : Double
    
}

and I made a class which contains an array of Answers

class TestResult {
    var name : String
    var answers : [Answer]
    var date : Date
    init(name: String, answers: [Answer],date: Date) {
        self.name = name; self.answers = answers; self.date = date;
    }
}

And I want to save TestResult instances to CoreData, I created an Entity called TestResultCoreData and added a Date and a String attribute to store name and date.

How should I save the Answer array?


Solution

  • In your core data model, create an entity called Answer and make the relationship a 1-to-many between the two entities TestResult and Answer.

    Or declare the answers attribute as Transformable data type in your data model.

    Core data model