Working with the insert() method in Swift

Updated: April 17, 2023 By: Khue Post a comment

Overview

In Swift, the insert() method has 2 variants: insert(_:at:) and insert(contentOf:at:).

insert(_:at:)

insert(_:at:) is used to insert a single element at the specified position in a given array. The syntax is:

array.insert(newElement, at: index)

The parameters are:

  • newElement – The element to insert into the array. The type of this element must match the type of the array’s elements.
  • at – The position at which to insert the new element. This parameter must be a valid index of the array or equal to its end index property.

insert(contentsOf:at:)

insert(contentsOf:at:) is used to insert the elements of another array or sequence at the specified position in a given array. The syntax is as follows:

array.insert(contentsOf: otherArray, at: index)

Where:

  • contentsOf – The array or sequence whose elements should be inserted into the array. The type of this parameter must match the type of the array’s elements.
  • at – The position at which to insert the new elements. This parameter must be a valid index of the array or equal to its end index property.

Examples

Inserting a new element into an array

This example inserts a new element after the first element of an array:

var products = ["product 1", "product 2", "product 3"]

// insert "product 1.5" after "product 1"
products.insert("product 1.5", at: 1)

print(products)

Output:

["product 1", "product 1.5", "product 2", "product 3"]

Prepending new elements to an array

Prepending new elements to an array means adding these elements to the beginning of the array.

var numbers = [1, 2, 3, 4, 5]

// prepend 0 to the beginning of the array
numbers.insert(0, at: 0)

// prepend -3, -2, -1 to the beginning of the array
numbers.insert(contentsOf: [-3, -2, -1], at: 0)

print(numbers)

Output:

[-3, -2, -1, 0, 1, 2, 3, 4, 5]

Inserting a new element after a specific element in an array

In this example, we have this array:

var items = ["a", "b", "c"]

What we want to achieve is to insert new item after b. Here’s the code:

var items = ["a", "b", "c"]

// insert "new item" after "b"
let index = items.firstIndex(of: "b")

if index != nil {
  items.insert("new item", at: items.index(after: index!))
  print(items)
} else {
  print("index not found")
}

Output:

["a", "b", "new item", "c"]