How do you convert a String to a CString in the Swift Language?

You can get a CString as follows:

import Foundation

var str = "Hello, World"

var cstr = str.bridgeToObjectiveC().UTF8String

EDIT: Beta 5 Update - bridgeToObjectiveC() no longer exists (thanks @Sam):

var cstr = (str as NSString).UTF8String

Swift bridges String and NSString. I believe this may be possible alternative to Cezary's answer:

import Foundation

var str = "Hello World"

var cstr = str.cStringUsingEncoding(NSUTF8StringEncoding)

The API documentation:

/* Methods to convert NSString to a NULL-terminated cString using the specified
   encoding. Note, these are the "new" cString methods, and are not deprecated 
   like the older cString methods which do not take encoding arguments.
*/
func cStringUsingEncoding(encoding: UInt) -> CString // "Autoreleased"; NULL return if encoding conversion not possible; for performance reasons, lifetime of this should not be considered longer than the lifetime of the receiving string (if the receiver string is freed, this might go invalid then, before the end of the autorelease scope)

There is also String.withCString() which might be more appropriate, depending on your use case. Sample:

var buf = in_addr()
let s   = "17.172.224.47"
s.withCString { cs in inet_pton(AF_INET, cs, &buf) }

Update Swift 2.2: Swift 2.2 automagically bridges String's to C strings, so the above sample is now a simple:

var buf = in_addr()
let s   = "17.172.224.47"
net_pton(AF_INET, s, &buf)

Much easier ;->

Tags:

Swift