Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift String to CChar

Tags:

string

swift

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?

like image 815
Josh The Geek Avatar asked Jun 23 '14 16:06

Josh The Geek


3 Answers

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
like image 91
Nate Cook Avatar answered Oct 31 '22 07:10

Nate Cook


Using Swift 3.0:

let cchar = "a".utf8CString[0]

(not sure when this was actually introduced, tho)

like image 2
Mazyod Avatar answered Oct 31 '22 08:10

Mazyod


With Swift 5, you can use one of the two following ways in order to get a collection of CChar from a String instance.


#1. Using Swift's utf8CString property

String has a utf8CString property. utf8CString has the following declaration:

var utf8CString: ContiguousArray<CChar> { get }

A contiguously stored null-terminated UTF-8 representation of the string.

The Playground sample code below shows how to use utf8CString:

let string = "Café 👍"
let bytes = string.utf8CString
print(bytes) // prints: [67, 97, 102, -61, -87, 32, -16, -97, -111, -115, 0]

#2. Using StringProtocol's cString(using:) method

Foundation provides String a cString(using:) method. cString(using:) has the following declaration:

func cString(using encoding: String.Encoding) -> [CChar]?

Returns a representation of the string as a C string using a given encoding.

The Playground sample code below shows how to get a collection of CChar from an string using cString(using:):

import Foundation

let string = "Café 👍"
let bytes = string.cString(using: String.Encoding.utf8)
print(bytes) // prints: Optional([67, 97, 102, -61, -87, 32, -16, -97, -111, -115, 0])
like image 1
Imanou Petit Avatar answered Oct 31 '22 09:10

Imanou Petit