Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Unicode Character to Int in Swift

A user asked the following question to one of my answers.

I have a unicode character \u{0D85}. How do I get the Int value from it?

I was going to refer them to another Stack Overflow Q&A but I couldn't find one. These refer to converting the other direction:

  • How to convert an Int to a Character in Swift
  • How can I get the Unicode codepoint represented by an integer in Swift?

And these seem to be asking how to convert a number in string form to an actual Int (as in converting "1" to 1).

  • Convert Character to Int in Swift 2.0
  • Convert Character to Int in Swift

Rather than try to fit my answer in a comment to the asker, I am going to provide an answer below. The Type of \u{0D85} is somewhat unclear but I will cover the various possibilities.

like image 556
Suragch Avatar asked Aug 04 '16 23:08

Suragch


2 Answers

Hex to Int

If you are starting with \u{0D85} and you know the hex value of the Unicode character, then you might as well write it in the following format because it is an Int already.

let myInt = 0x0D85                          // Int: 3461

String to Int

I assume, though, that you have "\u{0D85}" (in quotes), which makes it a String by default. And since it is a String, you can't be certain that you will only have a single Int value for the general case.

let myString = "\u{0D85}"

for element in myString.unicodeScalars {
    let myInt = element.value               // UInt32: 3461
}

I could have also used myString.utf16 and let myInt = Int(element), but I find it easier to deal with Unicode scalar values (UTF-32) when there is a possibility of things like emoji. (See this answer for more details.)

Character to Int

Swift Character, which is an extended grapheme cluster, does not have a utf16 or unicodeScalars property, so if you are starting with Character then convert it to a String first and then follow the directions in the String to Int section above.

let myChar: Character = "\u{0D85}"
let myString = String(myChar)
like image 188
Suragch Avatar answered Nov 13 '22 17:11

Suragch


With Swift 5, Unicode.Scalar has a value property. value has the following declaration:

A numeric representation of the Unicode scalar.

var value: UInt32 { get }

The following Playground sample codes show how to iterate over the unicodeScalars property of a Character or a String and print the Int32 value of each Unicode scalar:

let char: Character = "\u{0D85}"

for scalar in char.unicodeScalars {
    print(scalar.value)
}

/*
 prints: 3461
 */
let str: String = "\u{0D85}"

for scalar in str.unicodeScalars {
    print(scalar.value)
}

/*
 prints: 3461
 */
like image 39
Imanou Petit Avatar answered Nov 13 '22 19:11

Imanou Petit