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?

alexwlchan
  • 5,699
  • 7
  • 38
  • 49
Niko Adrianus Yuwono
  • 11,012
  • 8
  • 42
  • 64
  • 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... – Michael Jun 08 '14 at 16:47
  • Thanks for pointing that michael, I already edited my question – Niko Adrianus Yuwono Jun 08 '14 at 16:51

1 Answers1

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))
cobbal
  • 69,903
  • 20
  • 143
  • 156
  • 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. – ctietze Dec 27 '17 at 20:21