另一种选择是使用Dictionary,问题为Key,答案为Value:
let questions: [String : String] = [
"Question1" : "Answer1",
"Question2" : "Answer2",
"Question3" : "Answer3",
"Question4" : "Answer4",
"Question5" : "Answer5"
]
然后您可以像这样获得随机问答:
let randomQuestion = questions.randomElement()
然后访问问答文本:
let questionText = randomQuestion?.key ?? ""
let answerText = randomQuestion?.value ?? ""
关于您的下一个问题:
如何确保同一个问题不会出现多次,以及何时不再出现问题
您可以像这样从Dictionary Keys 构造一个Array。无论如何,这些键都是无序的,但如果你想重复,你应该把它们洗牌。
然后,您可以遍历随机数组中的每个问题:
在viewDidLoad 中设置您的属性,而不是在点击按钮时。
let randomQuestions = questions.keys.shuffled()
var currentQuestionIndex = 0
@IBAction func newQuestionButton(_ sender: Any) {
guard currentQuestionIndex != questions.count else {
return
// or reset your questionIndex and reshuffle.
}
// This will give you the Question (and Key)
let question = randomQuestions[currentQuestionIndex]
// Use the Key to extract out the answer (value) from the Dictionary
let answer = questions[question] ?? ""
// Update your labels
questionLabel.text = question
answerLabel.text = answer
// Increment your question index
currentQuestionIndex += 1
}