May 22 2020

How to insert an element to the start of an array.


If you have an array, you can add elements to it using the <span class=inline-code>.append</span> method on the array. This method will add the element to the end of the array. But, you don’t always want to do that. Sometimes you would want to add the element to the beginning of an array. There comes the <span class=inline-code>insert(at:)</span> method in place.


With the <span class=inline-code>insert(at:)</span> method, you can append an element to an array at any location of the array. For example, to the beginning of the array. Like this:

var array = ["is", "an", "array"]
array.insert("This", at:0) // The array is now: ["This",is","an", "array"]

This code will append the word “array” to the variable arrayat index 0, which is the beginning.

Of course, you can also pass it in at the second index, which is, using the example above, appending the element to the end.

If you pass in a Int to the at: argument that is larger than the number of elements in the array plus 1(In programming, you count from 0 upwards, so the first element is 0, second 1 etc.). If you do, then the app will crash as it cant append an element to index 5, if it only has 3 elements.