Swift 4 认为数组是空的,但不是

Swift 4 thinks array is empty when it's not

我试图从一个数组中取出所有元素,当它为空时恢复它。但是,当数组中还剩下 1 个元素时,"if .isEmpty" 检查表明数组为空。

这是我的代码:

import UIKit


// Here we store our quotes
let quotesMain = ["You can do anything, but not everything.",
                  "The richest man is not he who has the most, but he who needs the least.",
                  "You miss 100 percent of the shots you never take."]

var quoteList = quotesMain
var amountQuotes = quoteList.count


class ViewController: UIViewController {

    //Here we can see the quotes appear
    @IBOutlet weak var quotesDisplay: UILabel!


    // When user clicks the button/screen
    @IBAction func newQuote(_ sender: Any) {

        let randomPick = Int(arc4random_uniform(UInt32(quoteList.count)))
        print(randomPick)
        quotesDisplay.text = (quoteList[randomPick])

        quoteList.remove(at: randomPick)

        // empty check
        if quoteList.isEmpty {
            quotesDisplay.text = "Ohnoes! We ran out of quotes, time to restore"

            // ask for restore
            quoteList += quotesMain
        }
    }


}

基本上,相同的代码在操场上运行良好。任何人都可以看到我在这里失踪的东西。很抱歉,如果这真的很明显,我是新手。

这是因为您执行这些步骤的顺序:您正在挑选一个项目;显示它;从列表中删除它;然后查看列表是否为空。因此,当您只剩下一个项目时,您会显示它,但会立即将其从列表中删除,然后由于列表现在为空,因此会立即将其替换为 "out of quotes" 消息。

你可能想要这样的东西:

@IBAction func newQuote(_ sender: Any) {

    // empty check
    if quoteList.isEmpty {
        quotesDisplay.text = "Ohnoes! We ran out of quotes. Restoring. Try again."

        // ask for restore
        quoteList += quotesMain

        return
    }

    let randomPick = Int(arc4random_uniform(UInt32(quoteList.count)))
    print(randomPick)
    quotesDisplay.text = quoteList[randomPick]

    quoteList.remove(at: randomPick)
}