Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the Unicode codepoint represented by an integer in Swift?

So I know how to convert String to utf8 format like this

for character in strings.utf8 {
     // for example A will converted to 65
     var utf8Value = character
}

I already read the guide but can't find how to convert Unicode code point that represented by integer to String. For example: converting 65 to A. I already tried to use the "\u"+utf8Value but it still failed.

Is there any way to do this?

like image 1000
Niko Adrianus Yuwono Avatar asked Jun 08 '14 15:06

Niko Adrianus Yuwono


People also ask

How do I use Unicode Codepoint?

A code point is a number assigned to represent an abstract character in a system for representing text (such as Unicode). In Unicode, a code point is expressed in the form "U+1234" where "1234" is the assigned number. For example, the character "A" is assigned a code point of U+0041.

What is a Codepoint in UTF-8?

Code points allow abstraction from the term character and are the atomic unit of storage of information in an encoding. Most code points represent a single character, but some represent information such as formatting. UTF-8 is a “variable-width” encoding standard.

Which function is used to print the Unicode value of a character?

The ord function in python accepts a single character as an argument and returns an integer value representing the Unicode equivalent of that character.


1 Answers

If you look at the enum definition for Character you can see the following initializer:

init(_ scalar: UnicodeScalar)

If we then look at the struct UnicodeScalar, we see this initializer:

init(_ v: UInt32)

We can put them together, and we get a whole character

Character(UnicodeScalar(65))

and if we want it in a string, it's just another initializer away...

  1> String(Character(UnicodeScalar(65)))
$R1: String = "A"

Or (although I can't figure out why this one works) you can do

String(UnicodeScalar(65))
like image 133
cobbal Avatar answered Sep 28 '22 22:09

cobbal