我正在爲iOS開發一個測驗應用程序,並將問題保存在一個數組中,並將答案保存在另一個數組中。到目前爲止,我已經能夠用arc4random從問題數組中獲得一個隨機問題。但是,當我嘗試設置按鈕以顯示隨機答案選項時,它們與指定的問題不匹配。例如,question數組中index = 0處的問題與answers數組中index = 0處的answer數組一致,因此。如何隨時隨地產生正確的答案(換句話說,我如何確保它們都始終具有由arc4random方法或任何方法拉取的匹配索引)?如何將對與數組連接以包含相同的索引?
下面是我的一些代碼:
//random question generation function
func randomQuestion() {
index = Int(arc4random_uniform(UInt32(questions.count)))
questionLabel.text = questions[index]
let questions = ["Who is Thor's half brother?", "What is the name of Thor's hammer?", "What is Thor's father name?"]
//Each correct answer is placed at index 0 (right answers are Atum, Mjolinr, & Odin)
var answers = [["Atum", "Loki", "Red Norvell", "Kevin Masterson"], ["Mjolinr", "Uru", "Stormbreaker", "Odin's Staff"], ["Odin, "Sif", "Heimdall", "Balder"]]
//This variable is used in a later function that helps randomize wear the correct answer will be placed randomly from a set of buttons
var rightAnswerBox:UInt32 = 0
IBAction func buttonAction(_ sender: AnyObject) {
if (sender.tag == Int(rightAnswerBox)) {
print ("Correct!")
}
else {
wrongSeg()
print ("Wrong!")
}
if (currentQuestion != questions.count)
{
newQuestion()
}
}
override func viewDidAppear(_ animated: Bool)
{
newQuestion()
}
//function that displays new question
func newQuestion()
{
//countdown timer section
randomQuestion()
rightAnswerBox = arc4random_uniform(4)+1
//create a button
var button:UIButton = UIButton()
var x = 1
for index in 1...4
{
//creat a button
button = view.viewWithTag(index) as! UIButton
if (index == Int(rightAnswerBox))
{
button.setTitle(answers[currentQuestion][0], for: .normal)
}
else {
button.setTitle(answers[currentQuestion][x], for: .normal)
x += 1
}
}
currentQuestion += 1
}
而不是數組答案,你可以把問題的詞典作爲關鍵和答案作爲價值! –
你可以隨機化一本字典嗎? –
我還沒試過。但我瘦,你可以隨機排列字典鍵。 –