2D Arrays in Swift – Part 1

Multi-dimensional arrays are very useful for many programming tasks and 2D arrays are probably the most common form of the latter. They are used to represent spreadsheets, piano rolls, board game grids and so much more. And of course every image that we see on a device screen is essentially a matrix of rows and columns. So naturally we are going to use 2D arrays when coding in Swift. In this brief paragraph we are going to a quick look at what that entails. To follow along just paste the following code snippets into a Swift playground.

A simple 2D int array in C, Obj-C and so many other computer languages can be declared like this:

But – we’re not in Kansas anymore. Swift does not support this type of array declaration and that definitely causes a bit of a hiccup at first. What we can do, however, is use an array of arrays. Here is what such an animal would look like:

Under the hood this notation is an initialization of Swift’s Array class. Lets append two sub-arrays to this empty structure:

If we enter the code above into a playground we will get this result in the playground’s Assistant editor:
letter array: [[“a”, “b”, “c”], [“E”, “F”, “G”]]

Pretty close to what one would expect from a typical 2D array. We can subscript our letters array and append the sub-arrays individually:

After appending a letter to each of the two sub-arrays we get:
letter array: [[“a”, “b”, “c”, “d”], [“E”, “F”, “G”, “H”]]

Not too bad, but a bit clunky for when we need to initialize a 2D array in a for loop. For those cases the Array class comes in handy with its init(repeating:count:) initializer. To quote the docs, it creates a new array containing the specified number of a single, repeated value. And since we are dealing with 2D arrays we are going to nest it like so:

Here is the result shown in the Assistant editor:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

In one line of code we created symmetrical a 2D array of Ints and initialized all values to 0. We can subscript our intArray like so:

Here again is the result:
intArray: [[0, 7, 0], [0, 8, 0], [0, 0, 0]]

And of course we can use nested for loops as well in a manner that should look very familiar:

The result:
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

To summarize we can work with 2D arrays very easily in Swift. But other than in C for example where we can create arrays of basic types and then pass pointers to their first element we use the Array class.

[source code tested with Xcode 8.3.2 and Swift 3.1]