init(validating:as:)
Creates a new string by copying and validating the sequence of code units passed in, according to the specified encoding.
Declaration
init?<Encoding>(validating codeUnits: some Sequence, as encoding: Encoding.Type) where Encoding : _UnicodeEncodingParameters
- codeUnits:
A sequence of code units that encode a
String - encoding:
A conformer to
Unicode.Encodingto be used to decodecodeUnits.
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"