Reputation: 689
I have created a multidimensional array, but as soon as I try to add values to it at specific indexes it crashes with an index out of range
message. I think it has to do with the way I initialise the array - that I have to be more specific about what it can store etc. At this thread: Filling the Multidimensional Array in Swift it was suggested that I should initialise the array like this (obviously modified for my purposes):
var array: [[Int]] = Array(count:N, repeatedValue:Array(count:N, repeatedValue:0))
But I didn't get it to work, nor understood it properly. Below is the code I have. It crashes on the last code line.
var multiArray = [[Tile]]()
var gb = gameBoard.frame.width/4
for xItem in 0...3 { //DRAW TILE ON X AXIS
for yItem in 0...3 { //DRAW TILE ON Y AXIS
//CREATES A VARIABLE FOR TILE WITH PROPERTIES
tileView = Tile(frame: CGRect(x: (CGFloat(xItem) * gb), y: (CGFloat(yItem) * gb), width: gb, height: gb))
gameBoard.addSubview(tileView) //DRAWS TILE ONTO PARENT VIEW
multiArray[xItem][yItem] = tileView //CRASHES HERE WHEN TRYING TO ADD TO INDEX
}
}
Upvotes: 0
Views: 114
Reputation: 154563
You are really creating an array of arrays. You can't access indices that aren't created yet, so instead just create one column at a time and append items to it and then append each column array to the the multiArray
:
var multiArray = [[Tile]]()
var gb = gameBoard.frame.width/4
for xItem in 0...3 { //DRAW TILE ON X AXIS
var col = [Tile]()
for yItem in 0...3 { //DRAW TILE ON Y AXIS
//CREATES A VARIABLE FOR TILE WITH PROPERTIES
tileView = Tile(frame: CGRect(x: (CGFloat(xItem) * gb), y: (CGFloat(yItem) * gb), width: gb, height: gb))
gameBoard.addSubview(tileView) //DRAWS TILE ONTO PARENT VIEW
col.append(tileView)
}
multiArray.append(col)
}
The method you mentioned for initializing a multiArray works best if your array is filled with value types (such as Int
or Double
) and you have a reasonable default value (such as 0
). It doesn't work as well if your array will be holding class instances. You could make your array [[Tile?]]
and initialize it with nil
values, but then you'd have to deal with unwrapping the optionals later. The append
method is best for your case.
Upvotes: 2