Array insert() in Swift with examples


In this Swift programming article, you are going to learn all about the Swift Array insert() method with its usage and examples.

The array insert() method can insert an element into the existing array at a specific position by the index number.

Syntax of index() method

Below is the given syntax of insert() method in Swift:

array.insert(newElement, at: indexNumber)

In the above syntax, array is our array.

The index() method accepts two parameters newElement and indexNumber.

The newElement is the element to be added to our existing array and indexNumber is the index number where the element will be added.

Returned value of index() method

In Swift, the index() method doesn’t return any value. The only thing it does is update the current array by adding a new element inserted.

Examples of using index() method

Now it’s time to see the examples of using the method.

Example 1:

Below is our first example:

var colors = ["Green", "Yellow", "Pink"]

print(colors)

colors.insert("Red", at: 2)

print(colors)

Output:

["Green", "Yellow", "Pink"]
["Green", "Yellow", "Red", "Pink"]

In the above code, we have created an array colors that contains three names of colors. We are using the insert() method to add a new color Red to the index number 2 or third position.

Example 2: Using with startIndex and endIndex

We have already seen how to insert an element in a specific position by providing the index number. Well, if we want to insert an element at the very beginning or at the ending of the array, then we can also use the startIndex and endIndex instead of providing the index number 0 and the last index number.

The startIndex can find the index of the first element and the endIndex can find the index of the last element of an array.

Below is an example of how to insert an element at the starting using the startIndex:

var colors = ["Green", "Yellow", "Pink"]

print(colors)

colors.insert("Red", at: colors.startIndex)

print(colors)
["Green", "Yellow", "Pink"]
["Red", "Green", "Yellow", "Pink"]

Below is another example, where we are adding an element at the end using the endIndex:

var colors = ["Green", "Yellow", "Pink"]

print(colors)

colors.insert("Red", at: colors.endIndex)

print(colors)

Output:

["Green", "Yellow", "Pink"]
["Green", "Yellow", "Pink", "Red"]