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

# withTemporaryAllocation(of:capacity:_:)

Provides scoped access to an output span of the specified type and capacity.

```
func withTemporaryAllocation<T, R, E>(of type: T.Type, capacity: Int, _ body: @_lifetime(0: copy 0) (inout OutputSpan<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 output span being temporarily allocated.

`body`

A closure to invoke and to which the allocated output span
should be passed.

## Return Value

Whatever is returned by `body`.

## Discussion

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, it is passed an empty `OutputSpan`. `body` may
append or initialize elements in the output span. Any elements that have
been initialized when `body` returns are deinitialized automatically, and
deallocation is also automatic.

> Throws: Whatever is thrown by `body`.

---

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)