fredericdnd
fredericdnd

Reputation: 1008

Delete element from Array after use - Swift

My card is composed of 52 cards, so I created an array for them, and when the user click on the screen, a card is revealed.

I want that when a card is pulled, it can no longer be pulled in the future. I used removeAtIndex to remove the pulled card from the array. The function pullCard is called when the user touch the screen anywhere:

// Cards
let card1 = (1, "AS", "RULE 1")
let card2 = (2, "2", "RULE 2")
let card3 = (3, "3", "RULE 3")
let card4 = (4, "4", "RULE 4")
let card5... (to 52)

// Array
var cards = [
    card1,
    card2,
    card3,
    card4,
    card5... (to 52)
]

func pullCard() {
    let randomCard = Int(arc4random_uniform(UInt32(cards.count)))
    let cardsIndex = randomCard - 1
    let card = cards[cardsIndex]
    cards.removeAtIndex(cardsIndex)
}

Per example, the game pull the card 32, so it delete it from the array, and after if the game pull the same card, it crash because the card was deleted.

I tried to use an if statement :

if cards[cardsIndex] == nil {
    pullCard()
}

But it does not work. Please help me :)

Upvotes: 2

Views: 749

Answers (1)

Luca Angeletti
Luca Angeletti

Reputation: 59496

I think there is a problem here:

let cardsIndex = randomCard - 1

It should be:

let cardsIndex = randomCard

Infact you are generating randomCard as a random Int between 0 and (cards.count - 1).

So randomCard is already a valid index for cards, there's no need to subtract 1. When the random generated number does happen to be 0, you try to access the index -1 of cards and this is bad in this universe.

I admit this bug does not match exactly the description you gave in the question but I suggest you to fix it and try again.

Upvotes: 5

Related Questions