I am trying to use dispatch_queue_create with a dynamic String that I am creating at runtime as the first parameter. The compiler complains because it expects a standard c string. If I switch this to a compile time defined string the error goes away. Can anyone tell me how to convert a String to a standard c string?
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
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 ;->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With