OneBite.Dev - Coding blog in a bite size

Insert An Element At A Specific Index In An Array In Swift

Code snippet for how to Insert An Element At A Specific Index In An Array In Swift with sample and detail explanation

Inserting an element at a specific index in an array can be a common requirement in various coding scenarios. In this article, we will explore how we can accomplish this task using Swift, a powerful and intuitive programming language developed by Apple.

Code snippet to Insert An Element At a Specific Index In An Array In Swift

Here is a simple code snippet that illustrates this concept:

var numArray = [1, 2, 3, 4, 5]
let newElement = 6
let insertAtIndex = 2

numArray.insert(newElement, at: insertAtIndex)

When executed, this code will insert the newElement into the numArray at the index position specified by insertAtIndex.

Code Explanation for Insert An Element At a Specific Index In An Array In Swift

Let’s break down the above code to help us understand it better:

  1. Firstly, we declare and initialize a mutable array of integers named numArray. This array is initially populated with five elements - 1, 2, 3, 4, and 5.
var numArray = [1, 2, 3, 4, 5]
  1. We then declare and initialize an integer variable named newElement and assign it the value of 6. This is the element that we intend to inject into our numArray at a specified index.
let newElement = 6
  1. After that, we declare and initialize another integer variable named insertAtIndex and assign it the value of 2. This variable denotes the index position in the numArray where we wish to insert our newElement.
let insertAtIndex = 2
  1. Finally, we use the insert(_:at:) method of the Array class in Swift to insert newElement into numArray at the index specified by insertAtIndex.
numArray.insert(newElement, at: insertAtIndex)
  1. After the execution of the code, the new array will be [1, 2, 6, 3, 4, 5]

This is how we can easily insert an element at a specific index in an array in Swift. Note that array indices are zero-based, so an index of 2 actually refers to the third position in the array.

swift