Generic Instance Method

insert(contentsOf:at:)

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

Declaration

mutating func insert<C>(contentsOf newElements: C, at i: String.Index) where C : Collection, String.Element == C.Element

Parameters

newElements

The new elements to insert into the collection.

i

The position at which to insert the new elements. index must be a valid index of the collection.

Discussion

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

Here’s an example of inserting a range of integers into an array of the same type:

var numbers = [1, 2, 3, 4, 5]
numbers.insert(contentsOf: 100...103, at: 3)
print(numbers)
// Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]"

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

Complexity: O(m), where m is the combined length of the collection and newElements. If i is equal to the collection’s endIndex property, the complexity is O(n), where n is the length of newElements.

Relationships

Generic Constraints

  • C : Collection
    
  • Self.Element == C.Element
    

See Also

Inserting Characters

func insert(Character, at: String.Index)

Inserts a new character at the specified position.

func insert(Character, at: String.Index)

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

func insert<S>(contentsOf: S, at: String.Index)

Inserts a collection of characters at the specified position.

func reserveCapacity(String.CharacterView.IndexDistance)

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