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

# withTemporaryAllocation(byteCount:alignment:_:)

Provides scoped access to an output raw span with the specified byte count
and alignment.

```
func withTemporaryAllocation<R, E>(byteCount: Int, alignment: Int, _ body: @_lifetime(0: copy 0) (inout OutputRawSpan) throws(E) -> R) throws(E) -> R where E : Error, R : ~Copyable
```

## Parameters

`byteCount`

The number of bytes to temporarily allocate. `byteCount` must
not be negative.

`alignment`

The alignment of the new, temporary region of allocated
memory, in bytes. `alignment` must be a whole power of 2.

`body`

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

## Return Value

Whatever is returned by `body`.

## Discussion

This function is useful for cheaply allocating raw storage 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 `OutputRawSpan`. `body`
may append bytes to the output raw span. After `body` returns, deallocation
is 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)