代码之家  ›  专栏  ›  技术社区  ›  Jasper

Swift 4认为数组不是空的

  •  0
  • Jasper  · 技术社区  · 7 年前

    这是我的代码:

    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 回复  |  直到 7 年前
        1
  •  3
  •   Rob Md Fahim Faez Abir    7 年前

    这是因为你在做这些步骤的顺序:你在挑选一件物品;展示它;将其从列表中删除;然后查看列表是否为空。因此,当您只剩下一个项目时,您会显示它,然后立即将其从列表中删除,然后,因为列表现在为空,立即将其替换为“报价不足”消息。

    您可能需要以下内容:

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