1

I'm trying to append a value to a 2d array in Swift but it's throwing me an "index out of range" error on line 8

private var cards : [[Int]] = [[]]

init() {
    //Fill cards array by adding all cards
    for i in 0...12{
        for x in 0...3{
            cards[0].append(i+2)    //append card number... 2,3,4,5 etc
            cards[1].append(x)      //append card type... hearts, diamonds, clubs and spades
                                    //with a value which represents it (0, 1, 2 and 3)
        }
    }
}

Swift code

Lewy Willy
  • 81
  • 1
  • 4
  • 1
    maybe insed the secdon loop the single line of `cards.append([i+2, x])` would rather be a better approach in case of your array, but I am not sure that maches your expectations... however syntactically it is perfect. – holex Sep 20 '17 at 07:32
  • 1
    Related: https://stackoverflow.com/questions/39898434/swift-3-2d-array-of-int. – Martin R Sep 20 '17 at 07:46
  • In your case I'd suggest you to create a struct/class `Card` with `number: Int` and `type: String` properties. After that you can have only one array of cards with necessary data, easy extensible for new kind of properties in it. Just FYI – anatoliy_v Sep 20 '17 at 08:21

1 Answers1

4

You cannot access the inner arrays of cards using cards[0], since you initialize cards as an empty array of arrays and hence cards.count = 0, so cards[0] does not exist.

private var cards = [[Int]]()

init() {
    //Fill cards array by adding all cards
    for i in 0...12{
        for x in 0...3{
            cards.append([i+2,x])
        }
    }
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • This worked thanks! I'm confused as to why the append code on line 7 works fine but code on line 8 doesn't? both 0 and 1 have empty sizes. – Lewy Willy Sep 20 '17 at 07:37
  • I misunderstood your logic for the first time and hence the array dimensions were wrong in my first solution, check the updated answer. Btw storing card values like this is a really bad idea, you should create a `Card` struct and store a stack of cards as `[Card]`, not `[[Int]]`. – Dávid Pásztor Sep 20 '17 at 07:41