Instance Method

insert(_:at:)

Inserts a new element into the collection at the specified position.

Declaration

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

Parameters

newElement

The new element to insert into the collection.

i

The position at which to insert the new element. index must be a valid index into the collection.

Discussion

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

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

print(numbers)
// Prints "[1, 2, 3, 100, 4, 5, 200]"

Calling this method may invalidate any existing indices for use with this collection.

Complexity: O(n), where n is the length of the collection.

See Also

Adding Elements

func append(Array.Element)

Adds a new element at the end of the array.

func append(Element)

Adds an element to the end of the collection.

func append<S>(contentsOf: S)

Adds the elements of a sequence or collection to the end of this collection.

func append<S>(contentsOf: S)

Adds the elements of a sequence to the end of the array.

func insert(Array.Element, at: Int)

Inserts a new element at the specified position.

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.

func reserveCapacity(Int)

Prepares the collection to store the specified number of elements, when doing so is appropriate for the underlying type.