简体   繁体   English

如何在Swift 2.1中动态创建角色

[英]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 = ã . 然后,我要将转换为您的unicode值= ã I read in Swift Book this line: 我在Swift Book中读到了这一行:

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 : 首先将您的String转换为一个Int告诉Int它位于基数16,然后从Int创建一个UnicodeScalar ,最后从UnicodeScalar创建一个Character

let code = "00e3"
let character = Character(UnicodeScalar(Int(code, radix: 16)!))

If you'd prefer to have a String instead of a Character , then: 如果您希望使用String而不是Character ,那么:

let string = String(UnicodeScalar(Int(code, radix: 16)!))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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