Initializer

init(validatingUTF8:)

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

Declaration

init?(validatingUTF8 cString: UnsafePointer<CChar>)

Parameters

cString

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

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"

See Also

Creating a String from Unicode Data

init?(utf8String: UnsafePointer<CChar>)

Produces a string created by copying the data from a given C array of UTF8-encoded bytes.

init(utf16CodeUnits: UnsafePointer<unichar>, count: Int)

Returns an initialized String object that contains a given number of characters from a given array of Unicode characters.

init(utf16CodeUnitsNoCopy: UnsafePointer<unichar>, count: Int, freeWhenDone: Bool)

Returns an initialized String object that contains a given number of characters from a given array of UTF-16 Code Units

init<C, Encoding>(decoding: C, as: Encoding.Type)

Creates a string from the given Unicode code units in the specified encoding.