Swift Array insert()

The insert() method inserts an element to the array at the specified index.

Example

// create a list of vowels
var vowel = ["a", "e", "i", "u"]

// 'o' is inserted at index 3 (4th position) vowel.insert("o", at: 3)
print(vowel) // Output: ["a", "e", "i", "o", "u"]

insert() Syntax

The syntax of the array insert() method is:

array.insert(newElement, at: index)

Here, array is an object of the Array class.


insert() Parameters

The insert() method takes two parameters:

  • newElement - element to be inserted to array
  • index - the index where the element needs to be inserted

insert() Return Value

The insert() method doesn't return any value. It only updates the current array.


Example 1: Swift Array insert()

// create a array of prime numbers
var prime = [2, 3, 5, 7]

// insert 11 at index 4 prime.insert(11, at: 4)
print(prime)

Output

[2, 3, 5, 7, 11]

Example 2: Using insert() With startIndex and endIndex

// create a array of even
var even = [4, 6, 8]

// insert 2 at the starting index even.insert(2, at: even.startIndex)
// insert 10 at the end even.insert(10, at: even.endIndex)
print(even)

Output

[2, 4, 6, 8, 10]

Here,

  • startIndex - inserts element at the starting index i.e. index 0
  • endIndex - inserts element at the end of the array.