Swift附加到2d数组

时间:2017-09-20 07:22:36

标签: arrays swift

我正在尝试在Swift中向一个二维数组附加一个值,但它在第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

1 个答案:

答案 0 :(得分:3)

您无法使用cards访问cards[0]的内部数组,因为您将cards初始化为一个空的数组数组,因此cards.count = 0,因此cards[0]不存在。

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