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

# withUnsafeBytes(of:_:)

Invokes the given closure with a buffer pointer covering the raw bytes of
the given argument.

```
func withUnsafeBytes<T, E, Result>(of value: borrowing T, _ body: (UnsafeRawBufferPointer) throws(E) -> Result) throws(E) -> Result where E : Error, T : ~Copyable, Result : ~Copyable
```

## Parameters

`value`

An instance to temporarily access through a raw buffer pointer.

`body`

A closure that takes a raw buffer pointer to the bytes of `value`
as its sole argument. If the closure has a return value, that value is
also used as the return value of the `withUnsafeBytes(of:_:)`
function. The buffer pointer argument is valid only for the duration
of the closure’s execution. It is undefined behavior to attempt to
mutate through the pointer by conversion to
`UnsafeMutableRawBufferPointer` or any other mutable pointer type.
If you want to mutate a value by writing through a pointer, use
`withUnsafeMutableBytes(of:_:)` instead.

## Return Value

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

## Discussion

The buffer pointer argument to the `body` closure provides a collection
interface to the raw bytes of `value`. The buffer is the size of the
instance passed as `value` and does not include any remote storage.

---

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)