Jasper
Jasper

Reputation: 15

Swift 4 thinks array is empty when it's not

I'm trying to take all the elements from an array and when it's empty restore it. However, when there's still 1 element left in the array, the "if .isEmpty" check says the array is empty.

Here's my code:

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


}

Basically, the same code runs fine in the playground. Anyone sees what I'm missing here. I'm sorry if it's something really obvious, I'm new.

Upvotes: 0

Views: 448

Answers (1)

Rob
Rob

Reputation: 437682

It's because of the order that you're doing these steps: you are picking an item; showing it; removing it from the list; and then seeing if the list is empty. So when you have only item left, you're showing it, but then immediately removing it from the list and then, because the list is now empty, immediately replacing that with the "out of quotes" message.

You might want something like:

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

Upvotes: 3

Related Questions