The insert() method inserts an element to the array at the specified index.
Example
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()
Output
[2, 3, 5, 7, 11]
Example 2: Using insert() With startIndex and endIndex
Output
[2, 4, 6, 8, 10]
Here,
startIndex- inserts element at the starting index i.e. index 0endIndex- inserts element at the end of the array.