<!--
{
  "availability" : [
    "iOS: 12.2.0 -",
    "iPadOS: 12.2.0 -",
    "macCatalyst: 12.2.0 -",
    "macOS: 10.14.4 -",
    "tvOS: 12.2.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 5.2.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/Array/init(capacity:initializingWith:)",
  "metadataVersion" : "0.1.0",
  "role" : "Initializer",
  "symbol" : {
    "kind" : "Initializer",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:Sa8capacity16initializingWithSayxGSi_ys10OutputSpanVyxGzqd__YKXEtqd__YKcs5ErrorRd__lufc"
  },
  "title" : "init(capacity:initializingWith:)"
}
-->

# init(capacity:initializingWith:)

Creates an array with the specified capacity, and then calls the given
closure with an output span covering the array’s uninitialized memory.

```
init<E>(capacity: Int, initializingWith initializer: @_lifetime(span: copy span) (inout OutputSpan<Element>) throws(E) -> Void) throws(E) where E : Error
```

## Parameters

`capacity`

The number of elements to allocate
space for in the new array.

`initializer`

A closure that initializes the elements of the new array.

- Parameters:
  - span: An `OutputSpan` covering uninitialized memory with
    space for the specified number of elements.

## Discussion

Inside the closure, initialize elements by appending to the `OutputSpan`.
The `OutputSpan` keeps track of memory’s initialization state, ensuring
safety. Its `count` at the end of the closure will become the `count` of
the newly-initialized array.

> Note: While the resulting array may have a capacity larger than the
> requested amount, the `OutputSpan` passed to the closure will cover
> exactly the number of elements requested.

---

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)