<!--
{
  "availability" : [
    "iOS: 27.0.0 -",
    "iPadOS: 27.0.0 -",
    "macCatalyst: 27.0.0 -",
    "macOS: 27.0.0 -",
    "tvOS: 27.0.0 -",
    "visionOS: 27.0.0 -",
    "watchOS: 27.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/UniqueArray/insert(addingCount:at:initializingWith:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:s11UniqueArrayVsRi_zrlE6insert11addingCount2at16initializingWithySi_Siys10OutputSpanVyxGzqd__YKXEtqd__YKs5ErrorRd__lF"
  },
  "title" : "insert(addingCount:at:initializingWith:)"
}
-->

# 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.

```
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]
```

> Complexity: O(`self.count` + `count`)

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)