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

# withCString(encodedAs:_:)

Calls the given closure with a pointer to the contents of the string,
represented as a null-terminated sequence of code units.

```
func withCString<Result, TargetEncoding, E>(encodedAs targetEncoding: TargetEncoding.Type, _ body: (UnsafePointer<TargetEncoding.CodeUnit>) throws(E) -> Result) throws(E) -> Result where TargetEncoding : _UnicodeEncoding, E : Error
```

## Parameters

`targetEncoding`

The encoding in which the code units should be
interpreted.

`body`

A closure with a pointer parameter that points to a
null-terminated sequence of code units. If `body` has a return
value, that value is also used as the return value for the
`withCString(encodedAs:_:)` method. The pointer argument is valid
only for the duration of the method’s execution.

## Return Value

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

## Discussion

The pointer passed as an argument to `body` is valid only during the
execution of `withCString(encodedAs:_:)`. 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)