Swift 4-致命错误:索引超出范围 [英] Swift 4 - Fatal error: Index out of range

查看:250
本文介绍了Swift 4-致命错误:索引超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift 4中完成代码时,我需要帮助: 我想改组我的问题数组,但是它总是在一段时间后崩溃并显示以下消息:

I need help for finalize my code in Swift 4: I want to shuffle my questions array, but it always crashes after one time and shows this message:

致命错误:索引超出范围".

"Fatal error: Index out of range".

这是我的代码:

class ThirdViewController: UIViewController {
    var questions = ["A", "B", "C", "D", "E"]
    var answers = [["1","2","3"],["2","1","3"],["3","2","1"],["1","3","2"],["2","3","1"]]

    // Variables
    var rightAnswerPlacement:UInt32 = 0
    var shuffled = [String]();
    let randomNumber = Int(arc4random() % 5)

    // Label Question
    @IBOutlet weak var Label: UILabel!

    // Buttons
    @IBAction func Button(_ sender: UIButton) {
        if (sender.tag == Int(rightAnswerPlacement)) {
            print ("RIGHT")
            newQuestion()
        }
        else {
            print ("WRONG")
            newQuestion()
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        self.navigationController?.isNavigationBarHidden = true
        newQuestion()
    }

    // Functions
    func newQuestion() {
        Label.text = questions[randomNumber]   // ----------> Fatal error: Index out of range !!! -------------------------------------------------------------
        rightAnswerPlacement = arc4random_uniform(3)+1

        for _ in 0..<questions.count {
            let randomNumber = Int(arc4random_uniform(UInt32(questions.count)))
            shuffled.append(questions[randomNumber])
            questions.remove(at: randomNumber)
        }

    // Create a Button
    var Button:UIButton = UIButton()
    var x = 1
    for i in 1...3 {
        Button = view.viewWithTag(i) as! UIButton
        if (i == Int(rightAnswerPlacement)) {
            Button.setTitle(answers[randomNumber][0], for: .normal)
        }
        else {
            Button.setTitle(answers[randomNumber][x], for: .normal)
            x = 2
        }
    }
}

我的变量randomNumber似乎有问题,但我不知道如何解决. 我在论坛上看到过类似的问题,但没有答案可以解决我的问题.

It seems there is a problem with my variable randomNumber but I don't understand how to fix it. I have seen similar questions on the forum but no answer which resolves my problem.

推荐答案

问题是,当您删除数组的成员同时在for循环中通过同一数组时,array.count会减少,而您不可避免地会出现index out of range错误.

The problem is that when you delete a member of an array while going trough that same array in a for loop, the array.count decreases, and you inevitably get index out of range error.

此问题的常见解决方案是使用CountableRangereversed()函数从头到尾遍历一个数组:

The common solution of this problem is to go through an array from end to beginning, using the reversed() function of CountableRange:

for _ in (0..<questions.count).reversed(){

    //YOUR CODE
}

这篇关于Swift 4-致命错误:索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆