Extensions on Arrays

Prerequisites

Please make sure you watch first the following prerequisite videos:

So can we write extensions on arrays? Sure we can. Let’s discuss…

At their core, arrays are multi-value collections of elements, all under a single name.

But under the hood, arrays are also structs, and we have seen in the last video that arrays give us access to plenty of properties and functions out of the box. Count, isEmpty, and shuffle() are just a few examples.

But arrays being structs also means that we can add functionality to arrays with extensions, just like we can to any other struct or class object. Let’s add a boolean property that will tell us whether an array contains a single element or not. We can use the count property here, which is already a property that all arrays have out of the box, and compare its return value with the constant 1. When the count property is equal to 1, our new isSingle property will return true, otherwise it will return false.

We can skip being super explicit. Self in front of count is not really necessary, even though that is exactly what we mean. But the compiler can infer that on our behalf.

We can also skip writing the return keyword. Since we have a single line of code in our property closure, Swift can infer the fact that this line of code is the one returning a value.

Now, with this new functionality added to all arrays, calling isSingle on our initial numbers array will return false, of course. We do have more than 1 element in this array.

But, when we do have an array with only one element, like in this cities array example, calling cities.isSingle will return true this time.

And there you have it. We can add functionality to arrays in the same way we can add functionality to any struct or class object. And that is because in Swift, arrays are implemented under the hood as structs, which extend their core purpose of being a simple collection of elements accessed through an index, with an abundance of properties and functions, to which we can add our own as much as we desire, by adding extensions.