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

时间:2017-07-22 22:59:06

标签: ios arrays swift xcode

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

这是我的代码(适用于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"]]

1 个答案:

答案 0 :(得分:1)

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()
    }
}