我正在开发一个测验应用程序,在其中我有各种各样的问题和答案。答案选择通过与相应问题具有相同的索引与问题相关联(例如,答案数组中的第一个答案选择与问题数组的第一个索引一起使用,依此类推)。但是,我正在从问题数组中随机选择所要提问的问题,因此相应的答案不会随所显示的正确问题一起出现。随机选择和显示的问题中出现正确答案的最佳方法是什么?另外,如何防止已经回答的问题在测验失败并被重置之前不会再次被随机选择?谢谢。
这是我的代码:
import UIKit
class ViewController:UIViewController {
//random question generation function
func randomQuestion() {
index = Int(arc4random_uniform(UInt32(questions.count)))
questionLabel.text = questions[index]
}
//costants
let questions = ["Who is Thor's half brother?", "What is the name of Thor's hammer?"]
var answers = [["Atum", "Loki", "Red Norvell", "Kevin Masterson"], ["Mjolinr", "Uru", "Stormbreaker", "Odin's Staff"]]
//variables
var currentQuestion = 0
var rightAnswerBox:UInt32 = 0
var index = 0
//Question Label
@IBOutlet weak var questionLabel: UILabel!
//Answer Button
@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
randomImage()
}
我建议使用更合适的数据结构。
就像是:
class Question {
var id: Int
var questionText: String
var answers: [String]
var answered = false
}
然后,您可以将Question数组随机化。您可以跟踪所使用的索引,并在数组中向前移动直到结束。
在循环结束时,检查尚未回答的问题,删除已回答的问题(或创建一个新数组),然后重复该过程。
您可以通过数组枚举
var questions = [Question]()
//populate the array
for (index, question) in questions.enumerated() {
//This returns the question as well as the current index
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句