<!--
{
  "availability" : [
    "iOS: 18.0.0 -",
    "iPadOS: 18.0.0 -",
    "macCatalyst: 18.0.0 -",
    "macOS: 15.0.0 -",
    "tvOS: 18.0.0 -",
    "visionOS: 2.0.0 -",
    "watchOS: 11.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/String/init(validating:as:)-84qr9",
  "metadataVersion" : "0.1.0",
  "role" : "Initializer",
  "symbol" : {
    "kind" : "Initializer",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:SS10validating2asSSSgq__xmtcs16_UnicodeEncodingRzSTR_7ElementQy_8CodeUnitRtzr0_lufc"
  },
  "title" : "init(validating:as:)"
}
-->

# init(validating:as:)

Creates a new string by copying and validating the sequence of
code units passed in, according to the specified encoding.

```
init?<Encoding>(validating codeUnits: some Sequence, as encoding: Encoding.Type) where Encoding : _UnicodeEncoding
```

## Parameters

`codeUnits`

A sequence of code units that encode a `String`

`encoding`

A conformer to `Unicode.Encoding` to be used
to decode `codeUnits`.

## Discussion

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

The following example calls this initializer with the contents of two
different arrays—first with a well-formed UTF-8 code unit sequence and
then with an ill-formed UTF-16 code unit sequence.

```
let validUTF8: [UInt8] = [67, 97, 0, 102, 195, 169]
let valid = String(validating: validUTF8, as: UTF8.self)
print(valid ?? "nil")
// Prints "Café"

let invalidUTF16: [UInt16] = [0x41, 0x42, 0xd801]
let invalid = String(validating: invalidUTF16, as: UTF16.self)
print(invalid ?? "nil")
// Prints "nil"
```

---

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)