如何在Swift中间接显示给定的Unicode字符? [英] How to display indirectly given unicode character in Swift?
问题描述
在JSON数据文件中,我有一个Unicode字符,如下所示:
In a JSON data file, I have a unicode character like this:
{
"myUnicodeCharacter": "\\u{25a1}"
}
我知道如何从JSON文件读取数据.当它包含上面表示的字符时,就会发生此问题.
I know how to read data from JSON files. The problem occurs when it contains characters which are represented as above.
我将其读入字符串变量myUnicodeCharacterString中,该变量的值为"\ u {25a1}".顺便说一下,我无法在JSON数据文件中使用单个斜杠,因为在这种情况下,它无法将文件中的数据识别为正确的JSON对象,并返回nil.
I read it in to a String variable, myUnicodeCharacterString, which gets the value "\u{25a1}". I couldn't by the way use a single slash in the JSON data file because in such case it doesn't recognize the data in the file to be a proper JSON object, returning nil.
但是,当将值分配给用于显示它的对象(例如SKLabelNode)时,该值不会被编码为其图形表示形式:
However, the value is not encoded to its graphical representation when it’s assigned to something for displaying it, for example a SKLabelNode:
mySKLabelNode.Text = myUnicodeCharacterString // displays "\u{25a1}" and not a hollow square
问题归结为:
// A: direct approach, does works
let unicodeValueByValue = UnicodeScalar("\u{25a1}") // "9633"
let c1 = Character(unicodeValueByValue) // "a hollow square"
// B: indirect approach, this does not work
let myUnicodeString = "\u{25a1}"
let unicodeValueByVariable = UnicodeScalar(myUnicodeString) // Error: cannot find an initialiser
let c2 = Character(unicodeValueByVariable)
那么,如果代码中没有直接给出该字符,该如何显示格式为\ u {xxxx}的unicode字符?
So, how do I display a unicode character of the format "\u{xxxx}" if it's not directly given in code?
推荐答案
更好的方法是使用正确的\uNNNN
转义序列
JSON中的Unicode字符(有关详细信息,请参见 http://json.org ).
这是由NSJSONSerialization
自动处理的,您不必
必须转换一个十六进制代码.
A better way would be to use the proper \uNNNN
escape sequence
for Unicode characters in JSON (see http://json.org for details).
This is automatically handled by NSJSONSerialization
, and you don't
have to convert a hex code.
在您的情况下,JSON数据应为
In your case the JSON data should be
{
"myUnicodeCharacter" : "\u25a1"
}
这是一个完整的独立示例:
Here is a full self-contained example:
let jsonString = "{ \"myUnicodeCharacter\" : \"\\u25a1\"}"
println(jsonString)
// { "myUnicodeCharacter" : "\u25a1"}
let dict = NSJSONSerialization.JSONObjectWithData(jsonString.dataUsingEncoding(NSUTF8StringEncoding)!,
options: nil, error: nil) as [String : String]
let myUnicodeCharacterString = dict["myUnicodeCharacter"]!
println(myUnicodeCharacterString)
// □
这篇关于如何在Swift中间接显示给定的Unicode字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!