Error: “array index out of range” in multidimensional array

后端 未结 2 1703
北恋
北恋 2020-12-03 20:32

i have declared my array like

var tile = [[Int]]()

and after that i have initialize its value like

for (var index = 0; in         


        
2条回答
  •  Happy的楠姐
    2020-12-03 21:16

    As the commentators @C_X & @MartinR say, your array is empty. Here's how to initialise it as you want...

    var tile = [[Int]](count:4, repeatedValue: [Int](count: 4, repeatedValue: 0))
    
    for index in 0 ..< 4 {
        for sindex in 0 ..< 4 {
            tile[index][sindex] = 0 // no error here now...
            print("\(index) \(sindex)")
        }
    }
    

    ...of course, the for loops are now redundant, if you just want zeroes!

提交回复
热议问题