Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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?

like image 613
phoganuci Avatar asked Jun 08 '14 06:06

phoganuci


2 Answers

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
like image 93
Cezary Wojcik Avatar answered Sep 22 '22 13:09

Cezary Wojcik


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 ;->

like image 36
hnh Avatar answered Sep 19 '22 13:09

hnh