Josh The Geek Josh The Geek - 3 months ago 28
Swift Question

Swift String to CChar

How does one get a

in Swift? I need to call the following method:

- (void)registerOption:(NSString *)longOption shortcut:(char)shortOption requirement:(GBValueRequirements)requirement;

I can pass the ASCII form of the char, but that is annoying. Is there a simple way to get the char at a certain index in a string?


You can convert a Swift string to a Cstring and then just grab the first (and only) character:

var charString = "a"
var ccharOptional = charString.cStringUsingEncoding(NSUTF8StringEncoding)?[0]  // CChar?
var cchar = (charString.cStringUsingEncoding(NSUTF8StringEncoding)?[0])!       // CChar