How to manipulate arrays in Swift?
Prerequisites
Please make sure you watch first the following prerequisite videos:
So how to manipulate arrays in Swift? Let’s discuss…
Let’s start with this simple array: 35, 42, and 147. And let’s assign it to a property, let’s call it numbers. Due to type inference, this will be an array of integers and we don’t even have to declare it as such.
The first thing we need to do is to change this let into a var. Otherwise, our array will remain a constant that cannot be modified.
To add a new element to the end of the array, we call the append function. As many times as we need to.
And using the appendContentsOf function, we can append a whole new array to the end of our original array. Now this operation of appending an array to the end of another array is also called array concatenation, and it can be done in a few different ways using the plus operator, all with the same effect of putting together two different arrays into a single array.
The function removeLast() will remove the last element from the array.
But we can remove elements from anywhere in the array with the function removeAt() and indicating the desired index of the element to be removed. Let’s remember that the index starts at 0, not 1. So the element at index 2 will be in fact the third element in the array, with the value of 147 in our case, and that’s the element that will be removed.
How about inserting elements? We can insert an element anywhere in the array with the function insertAt(). We will need to specify the element to be inserted (let’s say the value of 20), and the index where we want it inserted.
One last function I would like to mention is removeAll(). This will remove every single element in the array, leaving the array completely empty.
These are just a few operations, the most common ones, that can be applied on arrays. Please consult the Apple documentation for more.
And there you have it: arrays can be easily manipulated with pre-defined functions such as append, appendContentsOf, removeLast, removeAt, insertAt, removeAll, and many other such functions.