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

# withUnsafeBytes(_:)

Calls the given closure with a pointer to the underlying bytes of
the viewed contiguous storage.

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

## Parameters

`body`

A closure with an `UnsafeRawBufferPointer`
parameter that points to the viewed contiguous storage.
If `body` has a return value, that value is also
used as the return value for the `withUnsafeBytes(_:)` method.
The closure’s parameter is valid only for the duration of
its execution.

## Return Value

The return value of the `body` closure parameter.

## Discussion

The buffer pointer passed as an argument to `body` is valid only
during the execution of `withUnsafeBytes(_:)`.
Do not store or return the pointer for later use.

---

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)