Contents

insert(addingCount:at:initializingWith:)

Inserts a given number of new items into this array at the specified position, using a callback to directly initialize array storage by populating an output span.

Declaration

mutating func insert<E>(addingCount newItemCount: Int, at index: Int, initializingWith initializer: @_lifetime(0: copy 0) (inout OutputSpan<Element>) throws(E) -> Void) throws(E) where E : Error

Parameters

  • newItemCount:

    The number of items to insert into the array.

  • index:

    The position at which to insert the new items. index must be a valid index in the array.

  • initializer:

    A callback that gets called at most once to directly populate newly reserved storage within the array. The function is called with an empty output span of capacity matching the supplied count, and it must fully populate it before returning.

Discussion

Existing elements in the array’s storage are moved towards the back as needed to make room for the new items.

If the array does not have sufficient capacity to hold the new elements, then this operation reallocates storage to extend its capacity, using a geometric growth rate.

var buffer = UniqueArray<Int>()
buffer.append([-999, 999])
var i = 0
buffer.insert(capacity: 3, at: 1) { target in
  while !target.isFull {
    target.append(i)
    i += 1
  }
}
// `buffer` now contains [-999, 0, 1, 2, 999]