Quick String for CChar

How to get char/ CCharin Swift? I need to call the following method:

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

I can pass an ASCII char form, but this is annoying. Is there an easy way to get char at a specific index in a string?

+4
source share
3 answers

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

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

Using Swift 3.0:

let cchar = "a".utf8CString[0]

(not sure when it was introduced, tho)

+1
source

In swift3 (3.0.2): let cchar = "abc".cString(using: .utf8)returns a CChar array.

0
source

Source: https://habr.com/ru/post/1545718/


All Articles