Search code examples
swiftutf-8utf8-decode

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?


Solution

  • 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))