Multidimensional Arrays in Swift

Categories:

Updated on 12/24/2018 for Swift 4.2.

Swift 4.2

The format for defining a 3-dimensional array in Swift 4.2 has changed!

Enumerating still works as follows:

Updated on 5/12/2018 for Swift 4.0.

Swift 4.0

The format for defining a 3-dimensional array in Swift 4.0 has not changed, and can still be accomplished with a variation of:

What has changed is the enumerate() method has been renamed to enumerated():

Updated on 1/24/2016 to support Swift 2.2, including removing C-style for loops and postfix increment operators.

Editor’s note: If you’re looking to branch out with Swift on a Linux system, check out our latest series of articles Swift on Linux and More Swift on Linux.

File this in the “Well I’ll be damned” category. While working on another project (I’m interested in a hybrid OS X and iOS project for generating Mandelbrot images) I came across the need to store Mandelbrot “escape values” in a two-dimensional array (e.g., a matrix). This matrix will be the basis for drawing the Mandelbrot plot, which each cell value being mapped to a color.

Of course I’m writing this code in Swift so I looked up how to declare a multidimensional array in the Swift Standard Library Reference.

Let’s take a look at the syntax for a unidimensional array, and yes, we’re using the “sugar” version of the syntax:

Simple enough. If we wanted to prefill our array with ones, we can do that with the (count:c, repeatedValue:v) construct:

The syntax may look out of place but it’s not really: [Int] is the name of the object we want to construct (an array of Ints) and we’re providing constructor arguments. It would be no different than writing self.anArray = IntegerArray(count:10, repeatedValue:1) if IntegerArray provided us with an array of integers.

Now enter the multidimensional array syntax. For an array of arrays of integers we would write:

The Swift reference also provides for basic initialization. Here we create a 3×3 identity matrix:

We’ll use this again in a basic class:

Executing this in the Playground gives us

which is what we would expect.

Now, I want to store information in a larger array (say 175 by 100), and want to initialize each element to zero. Here is the syntax:

Take a step back and let it soak in and it makes perfect sense. A two dimensional array is an array of arrays, so it stands to reason that the repeatedValue of the outer array will itself be an array. The repeatedValue of the inner array will be the base type you are storing in each cell.

Finally, a 3x3x3 array with each cell initialized to 1.

Swift 3.0

As mentioned in our Moving to Swift 3.0 post, the array initializer signature has changed from (count:repeatedValued:) to (repeating:count:). No sweat, let’s update our 3x3x3 array declaration:

Cake.

2 thoughts on “Multidimensional Arrays in Swift”

Leave a Reply

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