2D Arrays in Swift – Part 2

Last time we talked about 2D arrays in Swift. The topic is of relevance because in spite of its apparent C roots Swift handles 2D arrays quite differently. We presented two possible approaches for handling Swift arrays in a manner similar to what one might see in C and both of them involved the use of the Array class. More to the point we wanted a way to subscript our arrays as a convenient way to access array members.

As it turns out Swift has an immensely useful language feature called subscripts, sometimes also referred to as object subscripting. In our context object subscripting can be helpful in cases where we have our 2D array sitting in a class or struct. There is a little overhead before we can reap the benefits of this feature, but not too much.

Let’s take a look at what it would take to implement a basic structure for a Four in a Row game. In this game players take turns and try to connect 4 game pieces in either horizontal or vertical lines. The board typically consists of a grid of 6 rows and seven columns. Right up our alley.

The following code comes in three chunks that can be copied and pasted into a fresh Playground. Here is the main chunk – the FourInARow struct:

We start by declaring some field types in an enum. Nothing particularly interesting here other than the use of emojis maybe. Next we declare our grid and a couple of variables. We also add an init routine which enables us to reuse the grid with different dimensions. Take note that we initialize our grid here exactly the same way as discussed in our last post on 2D arrays.

Finally we have our declaration of the subscript methods. Subscripts are very flexible and can be used on a number of different types. Apples states that they are mostly used on one-dimensional structures.

We feed it two Ints and get back a FieldType. We might also have opted to declare a typealias to combine our x and y values.  At the heart of the subscript are the getter and setter methods that operate on our grid. In a more complex situation some error checking on the array boundaries would be a good addition, but for our purposes, we are good to go.

Next let’s add a little convenience extension that will make things look a little neater in our Playground:

All this does really is add a newline character at the sub-array edges so that our readout is somewhat more reminiscent of a board game. And here is some test code to initialize our new game and populate it with some sample moves:


Let’s take a look at our debug area:

Object subscripting is easy to set up, very convenient, very powerful and you should use it when dealing with 2D arrays. We only just scratched the surface in this brief post so maybe dig in and read the official documentation.