Swift – Insert an Element in Array at Specific Index
To insert an element in Swift Array at specific index, call
insert(_:at:) method. Pass the element as first argument and the index as value for
insert(_:at:) method inserts the given element (first argument) at specified index.
The syntax of
insert(_:at:) method that inserts an element to the array at the index is
We can only insert an element whose type is same as that of the elements in the array. Also, the index has to be within the index limits of the array.
In the following program, we will take an array
fruits, and insert an element
"guava" to this
fruits array at index
var fruits = ["apple", "banana", "cherry", "mango"] var anotherFruit = "guava" var index = 2 fruits.insert(anotherFruit, at:index) print(fruits)
anotherFruit is inserted in
fruits array at specified index
The index that we would like insert the element should be within the index range of the array. Otherwise, we would get runtime error.
Let us try to insert an element at index
8, when the array length is only
var fruits = ["apple", "banana", "cherry", "mango"] var anotherFruit = "guava" var index = 8 fruits.insert(anotherFruit, at:index) print(fruits)
In this Swift Tutorial, we learned how to insert an element in array, at specified index.