小编典典

如何在Swift中间接显示给定的Unicode字符?

json

在JSON数据文件中,我有一个Unicode字符,如下所示:

{
    ”myUnicodeCharacter”: ”\\u{25a1}”
}

我知道如何从JSON文件读取数据。当它包含如上所述表示的字符时,会发生此问题。

我将其读入字符串变量myUnicodeCharacterString中,该变量的值为“ \ u
{25a1}”。顺便说一下,我无法在JSON数据文件中使用单个斜杠,因为在这种情况下,它无法将文件中的数据识别为正确的JSON对象,返回nil。

但是,当将值分配给用于显示它的对象(例如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字符?


阅读 319

收藏
2020-07-27

共1个答案

小编典典

更好的方法是对\uNNNNJSON中的Unicode字符使用正确的转义序列(有关详细信息,请参见http://json.org)。这是由自动处理的NSJSONSerialization,您无需转换十六进制代码。

在您的情况下,JSON数据应为

{
    “ myUnicodeCharacter”:“ \ u25a1”
}

这是一个完整的独立示例:

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)
// □
2020-07-27