What Exactly Are Arrays?

So what exactly are arrays in Swift? Let’s discuss…

Arrays are basically data containers, but of a special kind. We are probably used to work with simple variables and constants like these, which hold a single value. These are single-value containers.

And we probably know about concepts like structs and class objects that hold multi-value data where each piece of data is accessed through a different key. These are keyed containers.

Arrays are un-keyed multi-value data containers, like a collection. They contain multiple data elements, all under a single name. And these elements can be integers, like in this examScores example, or strings like in this cities example, or whatever type of data we want.

We access individual elements using an index which indicates the position in the array. Be careful here, this index starts at 0, not at 1.

So, if in this case we want to access and print the element at index 2 (notice the index is enclosed in square brackets), we will get 147, because 147 is the third element in the array, which means index 2.

And in this other case, the element at index 1 will be “car”, the second element in the array.

Be very, very careful when accessing arrays. This numbers array has 4 elements, but index 4 does not exist. If you try to access index 4, you will get a nasty error and your app will crash.

And there you have it. Arrays are un-keyed multi-value data containers. Elements in the array can be of any data type and access to these elements is done through an index, which we need to remember it starts at 0, not at 1. We use square brackets to enclose the index of the element we want to access and we need to be careful not to access elements out of bounds.