Instance Method


Inserts a new element at the specified position.


mutating func insert(_ newElement: Element, at i: Int)



The new element to insert into the array.


The position at which to insert the new element. index must be a valid index of the array or equal to its endIndex property.


The new element is inserted before the element currently at the specified index. If you pass the array’s endIndex property as the index parameter, the new element is appended to the array.

var numbers = [1, 2, 3, 4, 5]
numbers.insert(100, at: 3)
numbers.insert(200, at: numbers.endIndex)

// Prints "[1, 2, 3, 100, 4, 5, 200]"

Complexity: O(n), where n is the length of the array. If i == endIndex, this method is equivalent to append(_:).


See Also

Adding Elements

func append(Element)

Adds a new element at the end of the array.

func insert<C>(contentsOf: C, at: Int)

Inserts the elements of a sequence into the collection at the specified position.

func replaceSubrange<C>(Range<Int>, with: C)

Replaces a range of elements with the elements in the specified collection.

func replaceSubrange<C, R>(R, with: C)

Replaces the specified subrange of elements with the given collection.

func reserveCapacity(Int)

Reserves enough space to store the specified number of elements.