With Swift 5, you can use one of the two following ways in order to get a collection of CChar from a String instance.
#1. Using Swift's utf8CString property
String has a utf8CString property. utf8CString has the following declaration:
var utf8CString: ContiguousArray<CChar> { get }
A contiguously stored null-terminated UTF-8 representation of the string.
The Playground sample code below shows how to use utf8CString:
let string = "Café "
let bytes = string.utf8CString
print(bytes) // prints: [67, 97, 102, -61, -87, 32, -16, -97, -111, -115, 0]
#2. Using StringProtocol's cString(using:) method
Foundation provides String a cString(using:) method. cString(using:) has the following declaration:
func cString(using encoding: String.Encoding) -> [CChar]?
Returns a representation of the string as a C string using a given encoding.
The Playground sample code below shows how to get a collection of CChar from an string using cString(using:):
import Foundation
let string = "Café "
let bytes = string.cString(using: String.Encoding.utf8)
print(bytes) // prints: Optional([67, 97, 102, -61, -87, 32, -16, -97, -111, -115, 0])