1

I am very new to Swift and this problem has got me stumped. I am trying to create a two-dimensional map. In init of my Map class, I need to create a two-dimensional array of another class called Grid.

This is what I have right now:

class Map: NSObject {
    var squares: [[Grid]]
    let MAXROWS = 200
    let MAXCOLUMNS = 200

    override init(){
         for r in 0...MAXROWS{
             for c in 0...MAXCOLUMNS{
                squares[r][c].append
            }
        }
    }

At the append function, it creates an error:

value of type "Grid" has no member "append"

How do I do this correctly?

0

3 Answers 3

3

Or if you don't like raw loops:

override init(){
    self.squares = Array<[Grid]>(
        repeating: Array<Grid>(
            repeating: Grid(),
            count: MAXCOLUMNS),
        count: MAXROWS
    )
}

edit: Like Alain T metnioned, this only works if Grid is a struct, otherwise the same instance would be used throughout the 2d array. This is because classes are passed by reference, and in this case, the same reference would be used every single time.

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

2 Comments

Hey Sander. Nice one! MM
This will produce rows with the same instance of the Grid() object in each column (given that Grid is a class). i.e. column 1 and column 2 of row 1 will be the same instance rather than two distinct instances of Grid.
0

You could also do it like this (because Grid is a class):

squares = (0..<MAXROWS).map{_ in (0..<MAXCOLUMNS).map{_ in Grid()}}

This uses the ranges as a means to "generate" the desired number of elements in the array. The map() function returns an entry for each generated number. Entries for rows are arrays of columns each containing a new instance of a Grid object. The "_ in" inside the map() closures tells the compiler that we are not actually using the value produced by the ranges.

Comments

0

try it:

class Map: NSObject {
var squares: [[Grid]]
let MAXROWS = 200
let MAXCOLUMNS = 200

override init(){
     for r in 0...MAXROWS{
        squares.append([])
         for c in 0...MAXCOLUMNS{
            squares[r].append(Grid())
        }
    }
}

1 Comment

I used this answer, however it generated an error because c is unused. I switched it from c to _ like it said and it no longer generates errors right there.

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.