Character and code conversion in Swift

Is it possible to convert directly between a Swift character and its Unicode numeric value? I.e:

var i:Int = ...  // A plain integer index.
var myCodeUnit:UInt16 = myString.utf16[i]
// Would like to say myChar = myCodeUnit as Character, or equivalent.

or...

var j:String.Index = ... // NOT an integer!
var myChar:Character = myString[j]
// Would like to say myCodeUnit = myChar as UInt16

I can say:

myCodeUnit = String(myChar).utf16[0]

but that means creating a new line for each character. And I do it thousands of times (text parsing), so this is a lot of new lines that are immediately discarded.

+4
source share
4 answers

The type Characteris a "Unicode grapheme cluster", which can be several Unicode code codes. If you want to use one Unicode code, you should use instead UnicodeScalar.

+4
source

:

/​​ String, :

var yourSwiftString = "甲乙丙丁"
for scalar in yourSwiftString.unicodeScalars {
    print("\(scalar.value) ")
}

/ UTF, NSString. .. int (32 , 21- ), Unicode:

var i = 22247
var unicode_str = NSString(bytes: &i, length: 4, encoding: NSUTF32LittleEndianStringEncoding)

, int, .

+4

Apple, Unicode, , Unicode . ? - .

for c in "hello" {
    // c is a unicode character of type Character
}

.

+1

, Unicode:

var char:Character = "a"
var unicodeValue = UnicodeScalar("a").value

I don’t know yet how to convert the unicode value back to Character.

-1
source

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


All Articles