2

Is there a single line equivalent for this Java code used to create a 2d array:

cells = new Cell[width][height];

in Swift 2.0?

Looking at various solutions here in Stack Overflow I have ended up with a multi-line monster of:

self.cells = [[Cell]]()
for (var col=0; col<height; col++){
    var newColumn = Array<Cell>.init(count: width, repeatedValue: Cell(x: 0,y: 0))
    self.cells.append(newColumn);
}

which creates an empty array for me. But I am quite sure that's not the right solution, just a duct tape kind of workaround.

1 Answer 1

3

No need to use a loop:

let inner = Array<Cell>(count: width, repeatedValue: Cell(x: 0,y: 0))
let cells = Array<[Cell]>(count: height, repeatedValue: inner)

It could be a one-liner of course:

let cells = Array<[Cell]>(count: height, repeatedValue: Array<Cell>(count: width, repeatedValue: Cell(x: 0,y: 0)))

But I prefer having separate statements for readability.

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

1 Comment

indeed the one liner is a mammoth size of statement :) will use the neat two lines version

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.