<!--
{
  "availability" : [
    "iOS: 8.0.0 -",
    "iPadOS: 8.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.10.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/Array/init(unsafeUninitializedCapacity:initializingWith:)",
  "metadataVersion" : "0.1.0",
  "role" : "Initializer",
  "symbol" : {
    "kind" : "Initializer",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:Sa27unsafeUninitializedCapacity16initializingWithSayxGSi_ySryxGz_Siztqd__YKXEtqd__YKcs5ErrorRd__lufc"
  },
  "title" : "init(unsafeUninitializedCapacity:initializingWith:)"
}
-->

# init(unsafeUninitializedCapacity:initializingWith:)

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

```
init<E>(unsafeUninitializedCapacity: Int, initializingWith initializer: (inout UnsafeMutableBufferPointer<Element>, inout Int) throws(E) -> Void) throws(E) where E : Error
```

## Parameters

`unsafeUninitializedCapacity`

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

`initializer`

A closure that initializes elements and sets the count
of the new array.

- Parameters:
  - buffer: A buffer covering uninitialized memory with room for the
    specified number of elements.
  - initializedCount: The count of initialized elements in the array,
    which begins as zero. Set `initializedCount` to the number of
    elements you initialize.

## Discussion

Inside the closure, set the `initializedCount` parameter to the number of
elements that are initialized by the closure. The memory in the range
`buffer[0..<initializedCount]` must be initialized at the end of the
closure’s execution, and the memory in the range
`buffer[initializedCount...]` must be uninitialized. This postcondition
must hold even if the `initializer` closure throws an error.

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

---

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)