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

后端 未结 2 1689
北恋
北恋 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条回答
  • 2020-12-03 20:51

    As per comments you know that you are asking for value at index in an empty array. If you want to initialise the array you should try something like this:

    for (var index = 0; index < 4; index++)
    {
        tile.append([])
        for (var sindex = 0; sindex < 4; sindex++)
        {
            tile[index].append(sindex)
    
            print("\(index) \(sindex)")
    
        }
    }
    
    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题