Multi-dimensional Arrays

Examples of declarations:

1. A 2D array of unspecified size, that contains integers:

var board = [[Int]]()
var board1:[[Int]] = [[Int]]()

The second version is more formal and more understandable: the left of the equal sign is saying: create a variable called board1, and of type 2-dimensional array. The RHS is saying: initialise the variable with a 2-dimensional array of no elements.

In the first (and preferred) version, the compiler assumes that ‘board‘ is of type 2-dimensional array, because it is being initialised with a 2-dimensional array (of no elements).

images2. A 2D array initialised to:
1  13
2
56 57 58

(where the first row has two columns (1 and 13),  the second row has one column (2), and the third row has three columns (56,57, and 58)):

var vCR = [[1,13],[2],[56,57,58]]
var vCR1:[[Int]] = [[1,13],[2],[56,57,58]]

As in the first example, the first version is preferred, while the second version is more formal, explicitly giving the variable a type (2-dimensional array).

3. A 3×3 array that is filled with 4’s:

var anArray =  [[Int]](count: 3, repeatedValue: [Int](count: 3,  repeatedValue: 4))

The above Right Hand Side says:

  • initialise anArray with a 2-dimensional array of integers (‘[[Int]]‘), and
  • fill each of the 3 rows (‘count:3‘)
  • with an integer array (‘repeatedValue:[Int]‘)
  • of 3 columns each containing ‘4’ (‘count:3 repeatedValue:4‘).

anArray equals [[4,4,4],[4,4,4],[4,4,4]]. That is, 3 rows, with each row containing a column of 3 elements ‘4’.

I found a re-read of Swift by Example, on single-dimensional arrays, handy at this point.

4. A 3x5x4 array that is filled with “a string”:

var aBigArray =  [[[String]]](count: 3, repeatedValue: [[String]](count: 5, repeatedValue: [String](count: 4, repeatedValue: "a string")))

image002

Leave a Reply

Your email address will not be published. Required fields are marked *