Josh The Geek Josh The Geek - 1 month ago 5
Swift Question

Swift String to CChar

How does one get a

char
/
CChar
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?

Answer

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