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

# withUnsafeMutableBytes(_:)

Calls the given closure with a pointer to the underlying bytes of the
array’s mutable contiguous storage.

```
mutating func withUnsafeMutableBytes<R>(_ body: (UnsafeMutableRawBufferPointer) throws -> R) rethrows -> R
```

## Parameters

`body`

A closure with an `UnsafeMutableRawBufferPointer`
parameter that points to the contiguous storage for the array.
If no such storage exists, it is created. If `body` has a return value, that value is also
used as the return value for the `withUnsafeMutableBytes(_:)` method.
The argument is valid only for the duration of the closure’s
execution.

## Return Value

The return value, if any, of the `body` closure parameter.

## Discussion

The array’s `Element` type must be a *trivial type*, which can be copied
with just a bit-for-bit copy without any indirection or
reference-counting operations. Generally, native Swift types that do not
contain strong or weak references are trivial, as are imported C structs
and enums.

The following example copies bytes from the `byteValues` array into
`numbers`, an array of `Int32`:

```
var numbers: [Int32] = [0, 0]
var byteValues: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00]

numbers.withUnsafeMutableBytes { destBytes in
    byteValues.withUnsafeBytes { srcBytes in
        destBytes.copyBytes(from: srcBytes)
    }
}
// numbers == [1, 2]
```

> Note: This example shows the behavior on a little-endian platform.

The pointer passed as an argument to `body` is valid only for the
lifetime of the closure. Do not escape it from the closure for later
use.

> Warning: Do not rely on anything about the array that is the target of
> this method during execution of the `body` closure; it might not
> appear to have its correct value. Instead, use only the
> `UnsafeMutableRawBufferPointer` argument to `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)