How to initialize a unichar variable in swift?

I have a function that requires an unichar parameter. But could not find a good way to initialize unichar in swift.

I am using the following method:

var delimitedBy:unichar = ("," as NSString).characterAtIndex(0)

Is there a better way to initialize unichar in swift?

+4
source share
3 answers

Swift can infer a type, and you do not need to distinguish the character Stringto NSString:

var delimitedBy = ",".characterAtIndex(0)
+6
source

Another possible solution:

var delimitedBy = first(",".utf16)!

(Note that this unicharis an alias of type for UInt16). This also works with string variables (which, of course, should not be an empty string).


Update for Swift 2 / Xcode 7:

var delimitedBy = ",".utf16.first!
+4
source

Swift 5 will be:

let delimeter = ",".utf16.first!
0
source

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


All Articles