Swift 4 - Fatal error: Index out of range

Swift 4 - Fatal error: Index out of range

我需要帮助来完成 Swift 4 中的代码: 我想打乱我的问题数组,但它总是在一次后崩溃并显示此消息:

"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 似乎有问题,但我不知道如何解决。 我在论坛上看到过类似的问题,但没有解决我问题的答案。

arc4random() returns0到4 294 967 295范围内的随机数

drand48() returns0.0到1.0之间的随机数

arc4random_uniform(N) returns0到N-1之间的随机数

尝试 让 randomNumber = Int(arc4random_uniform(5))

问题是,当您在 for 循环中遍历同一数组时删除数组的一个成员时,array.count 会减少,您不可避免地会遇到 index out of range 错误.

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

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

    //YOUR CODE
}