0

This is my code:

let slotImages = ["SlotImage1", "SlotImage2", "SlotImage3", "SlotImage4", "SlotImage5", "SlotImage6", "SlotImage7", "SlotImage8", "SlotImage9", "SlotImage10"]

    class cardsMinigame{
        let cardImage: UIImage
        let cardValue: Int
        init(cardImage: UIImage, cardValue: Int){
            self.cardImage = cardImage
            self.cardValue = cardValue
        }
    }

    var fakeCards = [[cardsMinigame](), [cardsMinigame](), [cardsMinigame]()]

And when adding a value to fakeCards, when using this code, I get the error "fatal error: index out of array" (the error is on this line as well):

fakeCards[i].append(cardsMinigame(cardImage: UIImage(named:"\(slotImages[random])")!, cardValue: random))

(where i is 0/1/2, random is < 10)

How can this occur? I am appending something to an empty array, I have no idea why it is out of index...

J. Doe
  • 12,159
  • 9
  • 60
  • 114
  • That's not how you append to an empty array in Swift. Use `append`. – JAL May 27 '17 at 01:06
  • That is what I am doing right?! – J. Doe May 27 '17 at 01:09
  • `fakecards[i]` is different than append. `fakecards[0]` will cause an exception if the array contains 0 objects. – JAL May 27 '17 at 01:09
  • Ok, but you said "use append"... now I am confused what to use – J. Doe May 27 '17 at 01:10
  • Yes, I'm saying use append, nothing about what I said has changed. I was just explaining what you were doing. If you try to access any index of an empty array, your code will crash. Always use `append` to add an object to an empty array. – JAL May 27 '17 at 01:12

0 Answers0