dimanche 6 septembre 2015

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 don't works. Please help me :)




Aucun commentaire:

Enregistrer un commentaire