Swift Language Practical Use-Case for Buffer Pointers


Example

Deconstructing the use of an unsafe pointer in the Swift library method;

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

Purpose:

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

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.

Source, Apple Inc., Swift 3 header file (For header access: In Playground, Cmd+Click on the word Swift) in the line of code:

import Swift

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

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

(Source, Apple Inc., Swift Header File Example)