I am developing a quiz app where I have a constant array of questions and answers. The answer choices are associated with the questions by having the same index as its corresponding question (For example the the first answer choices in the answers array go with the first index of the questions array and so on). However I am randomizing the selection of the question that is asked from the questions array so but the corresponding answers are not appearing with the right question that is shown. What is best way to go about having the right answer choices appear with the question that is randomly selected and shown? Also how would I prevent a question that has already been answered to not be randomly selected again until the quiz has failed and has been reset? Thanks.
Here's my code:
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()
}