<!--
{
  "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/replaceSubrange(_:addingCount:initializingWith:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:s11UniqueArrayVsRi_zrlE15replaceSubrange_11addingCount16initializingWithySnySiG_Siys10OutputSpanVyxGzqd__YKXEtqd__YKs5ErrorRd__lF"
  },
  "title" : "replaceSubrange(_:addingCount:initializingWith:)"
}
-->

# replaceSubrange(_:addingCount:initializingWith:)

Replaces the specified range of elements by a given count of new items,
using a callback to directly initialize array storage by populating
an output span.

```
mutating func replaceSubrange<E>(_ subrange: Range<Int>, addingCount newItemCount: Int, initializingWith initializer: @_lifetime(0: copy 0) (inout OutputSpan<Element>) throws(E) -> Void) throws(E) where E : Error
```

## Parameters

`subrange`

The subrange of the array to replace. The bounds of
the range must be valid indices in the array.

`newItemCount`

the maximum number of items to replace the old subrange.

`initializer`

A callback that gets called at most once to directly
populate newly reserved storage within the array. The function
is always called with an empty output span.

## Discussion

The number of new items need not match the number of elements being
removed.

This method has the same overall effect as calling

```
try array.removeSubrange(subrange)
try array.insert(
  addingCount: newItemCount,
  at: subrange.lowerBound,
  initializingWith: initializer)
```

Except it performs faster (by a constant factor), by avoiding moving
some items in the array twice.

If the array does not have sufficient capacity to perform the replacement,
then this reallocates storage to extend its capacity, using a geometric
growth rate.

If the callback fails to fully populate its output span or if
it throws an error, then the array keeps all items that were
successfully initialized before the callback terminated the prepend.

Partial insertions create a gap in array storage that needs to be
closed by moving newly inserted items to their correct positions given
the adjusted count. This adds some overhead compared to adding exactly as
many items as promised.

> Complexity: O(`self.count` + `newItemCount`) in addition to the complexity
> of the callback invocations.

---

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)