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

# withUTF8(_:)

Runs `body` over the content of this string in contiguous memory. If this
string is not contiguous, this will first make it contiguous, which will
also speed up subsequent access. If this mutates the string,
it will invalidate any pre-existing indices.

```
mutating func withUTF8<R, E>(_ body: (UnsafeBufferPointer<UInt8>) throws(E) -> R) throws(E) -> R where E : Error
```

## Discussion

Note that it is unsafe to escape the pointer provided to `body`. For
example, strings of up to 15 UTF-8 code units in length may be represented
in a small-string representation, and thus will be spilled into
temporary stack space which is invalid after `withUTF8` finishes
execution.

Complexity: O(n) if non-contiguous, O(1) if already contiguous

---

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)