Insert element to a specific index of an array in Swift

In this Swift tutorial, I will show you how to insert an element to a specific position of an array in Swift.

We will be using insert() function to add elements to an array.

We will cover these things:

  • How to add an element to a specific position.
  • How to add elements to the beginning of an array and to the end of an array.

Syntax of the function:

array.insert(elementToAdd, at:index)

elementToAdd – Here you can put any element you want to be added.

index– We can put the index position where we want to add that element.

Don’t bother if you don’t understand it. I will give you an example:

Let’s say, we have an array that holds elements [9,5,21,534]

Array index starts from 0. So, if we want to add an element (let’s say 100) just after 5 (index of 5 is 1), we can do that like this:

array.insert(100, at:2)

Add an element to a specific position in Swift

var array = [9,5,21,534]
array.insert(100, at: 1)
print(array)

Output:

[9, 100, 5, 21, 534]

You can add items to any position you would like using the above method.

Add an element to the beginning of an array

array.insert(elemetToAdd, at: array.startIndex)

See an example:

var array = [9,5,21,534]
array.insert(100, at: array.startIndex)
print(array)

Output:

[100, 9, 5, 21, 534]

Actually, array.startIndex returns the index of the first element that’s all. If you run the below code you will understand.

var array = [9,5,21,534]
print(array.startIndex)

Output:

0

Add an item to the end of an array in Swift

We can do this by using the same approach. We just need the index of the last element that’s all.

We can get that by using array.endIndex.

So our program will be like this:

var array = [9,5,21,534]
array.insert(100, at: array.endIndex)
print(array)

Output:

[9, 5, 21, 534, 100]

I have shown all of the above examples with integer items. Make sure you use double quotation to deal with string items like the below:

var array = ["hey","there","21","534"]
array.insert("codespeedy", at: array.endIndex)
print(array)

Output:

["hey", "there", "21", "534", "codespeedy"]

(We can not store integers and strings in the same array variable in Swift)

I have tested all of the methods on my machine. If you find any better option to do the same, feel free to let me know in the comment section.

You guys might be thinking is it possible to add multiple items or elements at once to an array. I will discuss that later in my blog. Stay tuned.

Leave a Reply

Your email address will not be published. Required fields are marked *