Reputation: 12683
I have a file with this string:
N\u00e3o informado
Than I read it and put in a variable
let myString = NSString(contentsOfFile: filename, encoding: NSUTF8StringEncoding)
print(mystring) // get "N\u00e3o informado"
Then I want to convert the \u00e3
to your unicode value = ã
. I read in Swift Book this line:
let text = "Voulez-vous un caf\u{65}\u{301}?"
And I tried create the same thing dynamicaly, but it didn't worked:
let substring = "00e3"
dinamic = "N\u{\(substring)}o informado" //This produce the equivalent
print(dinamic) // get "N\u{00e3}o informado" but I want "Não informado"
In the same way, this not work
let code = "00e3"
let caracter = Character("\u{\(code)}") //compile error
let caracter = Character("\\u{\(code)}") //runtime error
let number = 00e3
let caracter = Character(number) //compile error
let caracter = Character("\u{00e3}") //This work, but isn't dinamic
How can I do this?
Upvotes: 1
Views: 67
Reputation: 154603
First convert your String
to an Int
telling Int
that it is in base 16, then create a UnicodeScalar
from the Int
, and finally create the Character
from the UnicodeScalar
:
let code = "00e3"
let character = Character(UnicodeScalar(Int(code, radix: 16)!))
If you'd prefer to have a String
instead of a Character
, then:
let string = String(UnicodeScalar(Int(code, radix: 16)!))
Upvotes: 1