Search code examples
swiftstringunicodescalar

Deferent result in Unicode to String in Swift


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{?????}"


Solution

  • 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