Rachel Zuhl
Rachel Zuhl

Reputation: 49

Initializing Two Dimensional User-defined Arrays in Swift

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?

Upvotes: 1

Views: 90

Answers (3)

Sander Saelmans
Sander Saelmans

Reputation: 861

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.

Upvotes: 3

Masoud Roosta
Masoud Roosta

Reputation: 475

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

Upvotes: 0

Alain T.
Alain T.

Reputation: 42143

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.

Upvotes: 0

Related Questions