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?
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
Using Swift 3.0:
let cchar = "a".utf8CString[0]
(not sure when this was actually introduced, tho)
With Swift 5, you can use one of the two following ways in order to get a collection of CChar
from a String
instance.
Swift
's utf8CString
propertyString
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]
StringProtocol
's cString(using:)
methodFoundation 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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With