0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If Tile is a struct it would work. Just loop through and update each frame.
Ah, I see, so rather than specifying indexes I have to actually create a separate array and append it to the multi array. It works perfect! Thank you @vacawama for your assistance and for taking the time helping me out. Much appreciated! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.