<!--
{
  "availability" : [
    "iOS: 8.0.0 -",
    "iPadOS: 8.0.0 -",
    "macCatalyst: 8.0.0 -",
    "macOS: 10.10.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/ContiguousBytes/withUnsafeBytes(_:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "s:10Foundation15ContiguousBytesP010withUnsafeC0yqd__qd__SWKXEKlF"
  },
  "title" : "withUnsafeBytes(_:)"
}
-->

# withUnsafeBytes(_:)

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

```
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R
```

## Parameters

`body`

A closure with an <doc://com.apple.documentation/documentation/Swift/UnsafeRawBufferPointer> parameter that points to the contiguous storage for the type. If no such storage exists, the method creates it. If `body` has a return value, this method also returns that value. 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 following example copies the bytes from a string encoded using `utf8` into a buffer of `UInt8`:

```swift
let data = "Hello".data(using: .utf8)
var byteBuffer: [UInt8] = []
_ = data?.withUnsafeBytes { buffer in
    byteBuffer.append(contentsOf: buffer)
}

// byteBuffer = [72, 101, 108, 108, 111]
```

---

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)