<!--
{
  "availability" : [
    "iOS: 8.0.0 -",
    "iPadOS: 8.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.10.0 -",
    "swift: -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/String/init(validatingUTF8:)-208fn",
  "metadataVersion" : "0.1.0",
  "role" : "Initializer",
  "symbol" : {
    "kind" : "Initializer",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:SS14validatingUTF8SSSgSPys4Int8VG_tcfc"
  },
  "title" : "init(validatingUTF8:)"
}
-->

# init(validatingUTF8:)

Creates a new string by copying and validating the null-terminated UTF-8
data referenced by the given pointer.

```
init?(validatingUTF8 cString: UnsafePointer<CChar>)
```

## Parameters

`cString`


A pointer to a null-terminated sequence of UTF-8 code units.

## Discussion

This initializer does not try to repair ill-formed UTF-8 code unit
sequences. If any are found, the result of the initializer is `nil`.

The following example calls this initializer with pointers to the
contents of two different `CChar` arrays—the first with well-formed
UTF-8 code unit sequences and the second with an ill-formed sequence at
the end.

```
let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0]
validUTF8.withUnsafeBufferPointer { ptr in
    let s = String(validatingUTF8: ptr.baseAddress!)
    print(s)
}
// Prints "Optional("Café")"

let invalidUTF8: [CChar] = [67, 97, 102, -61, 0]
invalidUTF8.withUnsafeBufferPointer { ptr in
    let s = String(validatingUTF8: ptr.baseAddress!)
    print(s)
}
// Prints "nil"
```

> Note: This initializer has been renamed. Use
> `String.init?(validatingCString:)` instead.

---

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)