当它不是

时间:2017-07-21 01:38:54

标签: arrays swift is-empty

我试图从阵列中取出所有元素,当它为空时恢复它。但是,当数组中还剩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
        }
    }


}

基本上,相同的代码在游乐场中运行良好。任何人都能看到我在这里失踪的东西。对不起,如果它真的很明显,我就是新的。

1 个答案:

答案 0 :(得分:3)

这是因为您正在执行这些步骤的顺序:您正在挑选一个项目;显示它;将其从列表中删除;然后查看列表是否为空。因此,当您只剩下项目时,您将显示它,然后立即将其从列表中删除,然后,因为列表现在为空,立即将其替换为“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)
}