简体   繁体   中英

How dynamically create a Character in Swift 2.1

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 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM