---
title: "withCString(encodedAs:_:)"
framework: swift
role: symbol
role_heading: Instance Method
path: "swift/string/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.

## Declaration

```swift
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

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

## Discussion

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.

## See Also

### Getting C Strings

- [utf8CString](swift/string/utf8cstring.md)
- [withCString(_:)](swift/string/withcstring(_:).md)
