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

1

8

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?

Regulate answered 8/6, 2014 at 15:46 Comment(2)
you know, a single UTF8-byte is not always a character. In the case of 'A' it is, in the case of 'ñ' or 'ö' it is not... the question should be how to convert a unicode code point that is represented as an integer, into a Character...Mathura
Thanks for pointing that michael, I already edited my questionRegulate
C
11

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))
Correlate answered 8/6, 2014 at 21:36 Comment(1)
As for the last case: String(UnicodeScalar(65)) used to work but would now be String(describing: UnicodeScalar(65)). This indicates that this particular initializer treats UnicodeScalar as CustomStringConvertible, asking for its self-description in the end.Coppery

© 2022 - 2024 — McMap. All rights reserved.