我有一个领域数据库。这样数据库就更具可读性。我设计了如下问题库:
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
}
我试图提取答案并将它们放入元组数组(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))
}
}
我想要实现的是这样的,答案被拉出来等于我显然下面的那个不会编译
for i in 0...3 {
if i == question.correctAnswer {
currentAnswers.append((question.answer(i), true))
} else {
currentAnswers.append((question.answer(i), false))
}
}
答案 0 :(得分:1)
您可以使用Key path试试此代码
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))
}
}
答案 1 :(得分:0)
我设法找到了解决方法。只有一行额外的代码。 如果有人想要实现类似的东西,我希望这会有所帮助。
var currentAnswers = [(String, Bool)]()
let answers = [question.answer0, question.answer1, question.answer2, question.answer3]
for i in 0...3 {
if i == question.correctAnswer {
currentAnswers.append((answers[i], true))
} else {
currentAnswers.append((answers[i], false))
}
}
我一直在使用上面的元组进行真正的随机化,以便答案总是以不同的顺序显示在答案按钮上。