gpt4 book ai didi

ios - 如何将对连接到数组以包含相同的索引?

转载 作者:行者123 更新时间:2023-11-28 09:52:01 26 4
gpt4 key购买 nike

我正在为 iOS 开发一个测验应用程序,我将问题保存在一个数组中,将答案保存在另一个数组中。到目前为止,我已经能够使用 arc4random 使标签显示问题数组中的随机问题。但是,当我尝试设置按钮以显示随机答案选项时,它们与分配的问题不匹配。例如,问题数组中 index = 0 处的问题与答案数组中 index = 0 处的答案数组一致,依此类推。每当生成随机问题时,我如何才能找到正确答案显示的位置(换句话说,我如何确保它们始终具有由 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

最佳答案

使用 Dictionary 为适当的问题分配答案。

let QADictionary = ["Who is Thor's half brother?" : ["Atum", "Loki", "Red Norvell", "Kevin Masterson"],"What is the name of Thor's hammer?": ["Mjolinr", "Uru", "Stormbreaker", "Odin's Staff"], "What is Thor's father name?" : ["Odin", "Sif", "Heimdall", "Balder"] ]


//Get question list
let questionsList = Array(QADictionary.keys)
// Random question index
let index = Int(arc4random_uniform(UInt32(questionsList.count)))
// Fetch question from list
let question = questionsList[index]
// Assign to label
questionLabel.text = question

//Get the answer for the randomly chosen question. Because you question is the `Key` for the dictionary.
let answer = QADictionary[question]

关于ios - 如何将对连接到数组以包含相同的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45185763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com