1
目前我的代码从一个键和值的数组中抽出一个随机索引。然而,索引保持不变,并显示相同的键和值,但我想要它做的是显示一个随机索引迭代通过数组,并显示另一个不等于以前的随机索引的随机索引。我怎么能实现这个?如何通过整个数组来使我的随机索引进度?
这是我的代码(SWIFT为iOS):
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()
//array of keys/questions
var questionList = Array(listQuestions.QADictionary.keys)
//random question index
var rand = Int(arc4random_uniform(UInt32(questionList.count)))
var randAnswers = rand
//array of values/answers
var answerList = Array(listQuestions.QADictionary.values)
//button answer choices
var choices = answerList[randAnswers]
//fetch questions from list
let question = questionList[rand]
//function for new question and button titles
questionLabel.text = question
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()
}
}
使用此https://github.com/nvzqz/RandomKit也许可以帮助你 –