我正在为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
}
而不是数组答案,你可以把问题的词典作为关键和答案作为价值! –
你可以随机化一本字典吗? –
我还没试过。但我瘦,你可以随机排列字典键。 –