0

I am translating my String value to unicodeScalars with this down code, for example if I gave "A" as input I will get 65 as output, now that I know 65 is number of A, then I want give 65 to receive A again, but it gave e, I am sure I am mixing some topic together and also missing something, need some help for understanding why this is deferent and how can I use "\u{?????}" for returning my String, thanks

let string: String = "A"
let UInt32Value: UInt32 = string.unicodeScalars[string.startIndex].value
print(UInt32Value) // 65


let newString = "\u{65}"
print(newString) // e

ps: I know that there is official way of using unicodescalar to get the String back, but I am interested to "\u{?????}"

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
ios coder
  • 1
  • 4
  • 31
  • 91

2 Answers2

0

try to convert as follows

let ans =  String(UnicodeScalar(UInt8(65)))
print(ans)

I think the problem is, you are converting (A) string -> unicodescalar -> uint

and have to convert (65) uint -> unicodescalar -> string to get the original value

  • Yes, I know that, but as I asked in my question I want make this job with "\u{?????}", do you know how we can do with that as well? – ios coder Mar 01 '21 at 12:32
  • The use of `UInt8` initializer is pointless. `String(UnicodeScalar(65))` UInt8 conforms to Expressible ByIntegerliteral and Swift is a type inferred language. It will automatically infer the non optional UInt8 initializer – Leo Dabus Mar 01 '21 at 14:35
0

The \u{...} escape sequence uses hex:

Special characters can be included in string literals of both the single-line and multiline forms using the following escape sequences:

  • [...]
  • Unicode scalar (\u{n}), where n is a hexadecimal number that has one to eight digits

From the language reference.

So you need

"\u{41}"
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Is it right to say that I must convert 65 to 41 with a func that works with hexadecimal? – ios coder Mar 01 '21 at 13:04
  • @swiftPunk Just search "65 to hex" on google. Google can do hex conversions these days. – Sweeper Mar 01 '21 at 13:05
  • @swiftPunk Also note that this is a string _literal_, you can't do anything crazy like calling functions/referring to a variable i those `{}` brackets. You can only put, literally, 1 to 8 hexadecimal digits in there. – Sweeper Mar 01 '21 at 13:07
  • @swiftPunk That is to say, if you have the number 65 _at runtime_ (e.g. stored in a variable), you cannot use the `\u{...}` notation. In that case you can use Chandramohan's answer. `\u{...}` is only for when you know the number _at compile time_. – Sweeper Mar 01 '21 at 13:11
  • or using the string radix initializer `String(65, radix: 16)` and in the opposite direction `Int("41", radix: 16)` or literally type `0x41` – Leo Dabus Mar 01 '21 at 14:29