0

I have a script that loops through rounds of a card game, in this case I have 4 cards and 10 rounds.

When the cards array is empty I want to refill the cards array and shuffle it again and continue.

but somehow the refilling doesn't work and I get a error Index out of range

this is my code:

struct card {
    var name: String
    var val: Int
}

var allCards: [card] = []
allCards.append(card(name: "card A", val: 10))
allCards.append(card(name: "card B", val: 3))
allCards.append(card(name: "card C", val: 5))
allCards.append(card(name: "card D", val: 5))

class rounds {
    var roundNumber = 10
    var cards = allCards
    
    func playRounds() {
        switch self.roundNumber {
        case 10:
            self.cards.shuffle()
            self.roundNumber -= 1
        case 1...9:
            if cards.count == 0 {
                print("Cards shuffled")
                self.cards = allCards
                self.cards.shuffle()
            }
            self.cards.removeFirst()
            self.roundNumber -= 1
        default:
            print("End of game")
        }
    }
}

var playGame = rounds()

for _ in (0...10) {
    playGame.playRounds()
    print("Count of cards: \(playGame.cards.count)")
    print("Round: \(playGame.roundNumber)")
    print("Card name: \(playGame.cards[0].name)\n")

and this is my result in the debug window:

Count of cards: 4 Round: 9 Card name: card A

Count of cards: 3 Round: 8 Card name: card D

Count of cards: 2 Round: 7 Card name: card B

Count of cards: 1 Round: 6 Card name: card C

Count of cards: 0 Round: 5 Fatal error: Index out of range: file

in the if statement in case 1...9 I have a print("Cards Shuffled") that I don't see in de debug window, to me it looks that there is a problem in that if statement, but I don't understand what's wrong with this.

btw. the for loop at the bottom is for testing purpose, when this script works I'll assign this script to a button

1 Answer 1

2

You can't access index 0 of an array if it is empty so you need to check that first before accessing it

if (!playGame.cards.isEmpty) {
    print("Card name: \(playGame.cards[0].name)\n")
}

Another way to do it is to use first rather than index 0

guard let firstCard = playGame.cards.first else { continue }
print("Card name: \(firstCard.name)\n")
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.