gpt4 book ai didi

ios - 如何在调用索引后从数组中永久删除项目?

转载 作者:行者123 更新时间:2023-11-28 15:25:51 25 4
gpt4 key购买 nike

我的以下代码通过从字典中创建一个键和值数组并确保两个数组具有相同的索引来显示一个问题及其匹配的答案。但是,在随机选择一个问题及其答案后,我想将它们从各自的数组中永久删除,直到显示数组中的所有其他项目。简而言之,我如何确保在显示所有项目或直到用户回答错误之前不会再次显示问题和答案集?截至目前,当我想确保它根本不会显示两次时,我的代码只会确保不会连续两次选择相同的随机索引。

这是我的代码(适用于 iOS 的 swift):

func randomQuestion() {


//random question
var questionList = Array(QADictionary.keys)
var rand = Int(arc4random_uniform(UInt32(questionList.count)))
questionLabel.text = questionList[rand]




//matching answers
var answerList = Array(QADictionary.values)
var choices = answerList[rand]




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

}

func removePair() {
questionList.remove(at: rand)
answerList.remove(at: rand)


}


randomImage()

}
}


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"]]

最佳答案

将您的 questionList 移动到 viewController 的一个属性,以便它从 randomQuestion 的一次调用到下一次调用保持不变。只有在它为空时才重新加载它。

使用字典查找匹配的答案,而不是使用第二个数组。

var questionList = [String]()

func randomQuestion() {

//if no more questions, reload the questionList
if questionList.isEmpty {
questionList = Array(QADictionary.keys)
}

var rand = Int(arc4random_uniform(UInt32(questionList.count)))
questionLabel.text = questionList[rand]

//matching answers
var choices = QADictionary[questionList[rand]]!

questionList.remove(at: rand)

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

}

func removePair() {
questionList.remove(at: rand)
}

randomImage()
}
}

关于ios - 如何在调用索引后从数组中永久删除项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45260021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com