0

I have the below Java code which I need to convert to Swift. First one is simply initializing a 2D array with a number of rows and columns.

double[][] VAR1 = new double[5][10];

Second one is initializing a 2D array with some initial values.

double[][] VAR2 = new double[][]{ {2.1, 4.3}, {5.4, 8.9},};

I can't figure out how to do the first one.

But I have a shot at the second one. Not sure if it's correct though.

var var2: [[Double]] = [[2.1], [4.3], [5.4], [8.9]]
Isuru
  • 30,617
  • 60
  • 187
  • 303

1 Answers1

2

You're close - should be like this:

var var2: [[Double]] = [[2.1, 4.3], [5.4, 8.9]]

And for the first one:

var var1: [[Double]] = Array(repeating: Array(repeating: 0.0, count: 10), count: 5)
creeperspeak
  • 5,403
  • 1
  • 17
  • 38
  • Oh right! Thanks. I corrected the second one. For the first one though, 5 and 10 aren't values, they're to specify the _capacity_ I think. I just took the words rows and columns out of a similar Java [question](http://stackoverflow.com/q/12231453/1077789). – Isuru Mar 02 '17 at 18:30
  • Ah, ok. In that case, since you don't need to specify capacity in Swift, you could just say `var var1 = [[Double]]()`. Adding the () at the end initializes an empty array of the specified type. – creeperspeak Mar 02 '17 at 18:32
  • I see. But if we need to, is there a way to specify the capacity or it's simply impossible in Swift? – Isuru Mar 02 '17 at 18:36
  • 2
    Yes, you can do that like this `var var1 = [[Double]](repeating: [Double](repeating: Double(), count: 10), count: 5)`. This creates a "2D" array (Swift people don't refer to them as such) with 5 "rows", with each row containing 10 "columns" of type `Double`. I don't often see people doing this in Swift, but of course you are welcome to do so. – creeperspeak Mar 02 '17 at 18:41
  • Got it! Thank you. – Isuru Mar 02 '17 at 18:45