简体   繁体   中英

Swift append to 2d array

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

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])
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM