简体   繁体   中英

How to store large arrays of structs - Swift

I am creating a quiz app which has 2 modes (lets call them A & B). Each mode draws 50 random random questions from an array of structs with over 250 values. To clarify, mode A and mode B both have seperate question pools with over 250 questions, so in total there is around 500 questions.

How do I best store these arrays of structs so I can pull them into my View Controller when the user selects the desired test.

Below is an example of the question pool for a mode.

// Question models

class QuizQuestion {

    let question: String!
    let answer: Bool!
    let explanation: String!
    var usersAnswer: Bool?
    var answerSubmitted: Bool?

    init(question: String, answer: Bool, explanation: String) {
        self.question = question
        self.answer = answer
        self.explanation = explanation
    }
}

    var questions = [

    QuizQuestion(question: "Do I like coffee?", answer: true, explanation: "Because it's awesome!"),
    QuizQuestion(question: "Is bacon god's gift to mankind?", answer: true, explanation: "Because it's awesome!"),
    QuizQuestion(question: "Should I take a nap right now?", answer: true, explanation: "You gotta review some code!"),
    QuizQuestion(question: "Should I take a nap right now?", answer: true, explanation: "You gotta review some code!")
]

The two ways to store the questions on disk are: 1) Core data 2) Sqlite

I would suggest the following architecture to retrieve the stored questions:

1) Store 250 questions in core data/sqlite with each question associated with a number 1-250.

2) When you need to select 50 questions randomly, generate 50 random numbers and retrieve the question associated with the random numbers you generated.

This approach will help you store more than 250 questions too.

Explaining core data or sqlite is beyond the scope of this answer. You can easily find tutorials for these online.

About saving in a swift file: You can declare a struct in a swift file with the questions. I think this would work for 250 questions but the problem with this approach is that it would take up memory. So this is not scalable in case you want to add more questions later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM