Search code examples
swiftrealm

Pull out data from a numbered variable using a loop in swift


I have a realm database. So that the database is more readable. I have designed the questionbank as follows:

class Question: Object {
    @objc dynamic var id: Int = 0
    @objc dynamic var name: String = ""
    @objc dynamic var answered: Bool = false
    @objc dynamic var lastAnswer: Bool = false
    @objc dynamic var howManyTimesAnswered: Int = 0
    @objc dynamic var answer0: String = ""
    @objc dynamic var answer1: String = ""
    @objc dynamic var answer2: String = ""
    @objc dynamic var answer3: String = ""
    @objc dynamic var correctAnswer: Int = 0
    let parentCategory = LinkingObjects(fromType: Category.self, property: "questions") //back relationship to category
}

I am trying to pull out the answers and putting them into an array of tuples (String, Bool)

 var currentAnswers = [(String, Bool)]()
    for i in 0...3 {
        if i == question.correctAnswer {
            currentAnswers.append(("question.answer2", true))
        } else {
            currentAnswers.append((question.answer1, false))
        }
    }

what I want to achieve is something like this where the answer pulled out is equal to i obviously the one below will not compile

    for i in 0...3 {
        if i == question.correctAnswer {
            currentAnswers.append((question.answer(i), true))
        } else {
            currentAnswers.append((question.answer(i), false))
        }
    }

Solution

  • You can use Key path Try this code

      var currentAnswers = [(String, Bool)]()
        for i in 0...3 {
            if i == question.correctAnswer {
                currentAnswers.append((question.value(forKey: "answer\(i)") as! String, true))
            } else {
                currentAnswers.append((question.value(forKey: "answer\(i)") as! String, false))
            }
        }