In this Swift programming tutorial, you will learn how to add or insert an element to the beginning of a Swift array.
Inserting a new item to the very start of a Swift array is quite easy. We can use the
insert(_:at:) method to perform this task. In this method, we have to pass the element with the index number where our new element will be added.
As we know, the index of the first element of an array is always 0, so we have to add the new element to the index 0.
Now let’s see the code example:
var cities = ["Paris", "Miami", "Amsterdam"] print(cities) cities.insert("Bengaluru", at: 0) print(cities)
["Paris", "Miami", "Amsterdam"]
["Bengaluru", "Paris", "Miami", "Amsterdam"]
In the above code, we have added a new array item in the index 0. We set the index 0 to add the new element at the very beginning:
cities.insert("Bengaluru", at: 0)
In Swift, the array
insert() method used to insert elements to the existing array at the specified index. In our case, we are using the insert() method to add a new item at the 0 index.
You can see that in the output, the newly added element appear at the start of the array. That means we did our task successfully. You can notice that all other elements move by one index number as the new element take the first position.
Note that, we can use the array insert() to insert an element to any position by providing the index number in the parameter property.