<!--
{
  "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/OutputRawSpan/withUnsafeMutableBytes(_:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:s13OutputRawSpanV22withUnsafeMutableBytesyq_q_Sw_SiztxYKXExYKs5ErrorRzRi__r0_lF"
  },
  "title" : "withUnsafeMutableBytes(_:)"
}
-->

# withUnsafeMutableBytes(_:)

Call the given closure with the unsafe buffer pointer addressed by this
OutputRawSpan and a mutable reference to its count of initialized bytes.

```
mutating func withUnsafeMutableBytes<E, R>(_ body: (UnsafeMutableRawBufferPointer, inout Int) throws(E) -> R) throws(E) -> R where E : Error, R : ~Copyable
```

## Parameters

`body`

A closure that can read from and write to the
buffer and update the initialized count.

## Return Value

The return value of the `body` closure.

## Discussion

This method provides a way to process or populate an `OutputRawSpan` using
unsafe operations, such as dispatching to code written in legacy
(memory-unsafe) languages.

The supplied closure may process the buffer in any way it wants; however,
when it finishes (whether by returning or throwing), it must leave the
buffer in a state that satisfies the invariants of the output span:

1. The inout integer passed in as the second argument must be the exact
   number of initialized bytes in the buffer passed in as the first
   argument.
2. These initialized bytes must be located in a single contiguous
   region starting at the beginning of the buffer. The rest of the buffer
   must hold uninitialized memory.

This function cannot verify these two invariants, and therefore
this is an unsafe operation. Violating the invariants of `OutputRawSpan`
may result in undefined behavior.

---

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)