I am developing a iOS quiz app where the questions and answers are stored in a dictionary of type [String : Array] where the questions are the keys and the answers to that question are its values. I have found out how to randomly display question by creating an array of the dictionary's keys and setting a label text as the the random chosen key. However I am having trouble setting the values of the chosen key as title's for the buttons? There are four values per key and four buttons, what would be the most efficient and simplest way to display the answer values as titles as buttons?
Here is my code (when I run the simulator the four buttons titles just say "button" even though I have a setTitle function in my code):
class QuestionDetails {
let QADictionary = [
"Who is Thor's brother?" : ["Atum", "Loki", "Red Norvell", "Kevin Masterson"],
"What is the name of Thor's hammer?" : ["Mjolinr", "Uru", "Stormbreaker", "Thundara"],
"Who is the father of Thor?" : ["Odin", "Sif", "Heimdall", "Balder"]
]
}
//get question list
func questionWithAnswers() {
let listQuestions = QuestionDetails()
var questionList = Array(listQuestions.QADictionary.keys)
//random question index
var rand = Int(arc4random_uniform(UInt32(questionList.count)))
var randAnswers = rand
//random answer index
var answerList = Array(listQuestions.QADictionary.values)
var choices = answerList[randAnswers]
//fetch questions from list
let question = questionList[rand]
questionLabel.text = question
//function for new question and button titles
func showQuestion() {
rightAnswerBox = arc4random_uniform(4)+1
//create button
var button:UIButton = UIButton()
var x = 1
for index in 1...4
{
button = view.viewWithTag(index) as! UIButton
if (index == Int(rightAnswerBox))
{
button.setTitle(choices[0], for: .normal)
}
else {
button.setTitle(choices[x], for: .normal)
x += 1
}
randomImage()
}
}
}