如何创建单个字符串

时间:2016-10-12 08:49:16

标签: swift swift3

我在Swift游乐场重现了这个问题,但还没有解决它......

我想在UILabel中打印一系列字符。如果我明确声明了这个角色,它就可以了:

// This works.
let value: String = "\u{f096}"
label.text = value  // Displays the referenced character.

但是,我想构造String。下面的代码似乎产生与上面一行相同的结果,但它没有。它只生成字符串\u{f096}而不是它引用的字符。

// This doesn't work
let n: Int = 0x95 + 1
print(String(n, radix: 16))  // Prints "96".
let value: String = "\\u{f0\(String(n, radix: 16))}"
label.text = value  // Displays the String "\u{f096}".

我可能错过了一些简单的事情。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

如何停止使用字符串转换voodoo并使用标准库类型UnicodeScalar

  

您也可以直接从其数字表示创建Unicode标量值。

let airplane = UnicodeScalar(9992)
print(airplane) 
// Prints "✈︎"

UnicodeScalar.init实际上返回了可选值,因此您必须将其解包。

如果您需要String,只需将其通过Character类型转换为字符串。

let airplaneString: String = String(Character(airplane)) // Assuming that airplane here is unwrapped
相关问题