<!--
{
  "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/withUnsafeTemporaryAllocation(of:capacity:_:)",
  "metadataVersion" : "0.1.0",
  "role" : "Function",
  "symbol" : {
    "kind" : "Function",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:s29withUnsafeTemporaryAllocation2of8capacity_q_xm_Siq_SryxGq0_YKXEtq0_YKs5ErrorR0_Ri_zRi__r1_lF"
  },
  "title" : "withUnsafeTemporaryAllocation(of:capacity:_:)"
}
-->

# withUnsafeTemporaryAllocation(of:capacity:_:)

Provides scoped access to a buffer pointer to memory of the specified type
and with the specified capacity.

```
func withUnsafeTemporaryAllocation<T, R, E>(of type: T.Type, capacity: Int, _ body: (UnsafeMutableBufferPointer<T>) throws(E) -> R) throws(E) -> R where E : Error, T : ~Copyable, R : ~Copyable
```

## Parameters

`type`

The type of the elements in the buffer being temporarily
allocated.

`capacity`

The capacity of the buffer pointer being temporarily
allocated.

`body`

A closure to invoke and to which the allocated buffer pointer
should be passed.

## Return Value

Whatever is returned by `body`.

## Discussion> Throws: Whatever is thrown by `body`.

This function is useful for cheaply allocating storage for a sequence of
values for a brief duration. Storage may be allocated on the heap or on the
stack, depending on the required size and alignment.

When `body` is called, the contents of the buffer pointer passed to it are
in an unspecified, uninitialized state. `body` is responsible for
initializing the buffer pointer before it is used *and* for deinitializing
it before returning, but deallocation is automatic.

The buffer pointer passed to `body` (as well as any pointers to elements in
the buffer) must not escape. It will be deallocated when `body` returns and
cannot be used afterward.

---

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)