How can I get the Unicode codepoint represented by an integer in Swift?

放肆的年华 提交于 2019-12-09 16:24:21

问题


So I know how to convert String to utf8 format like this

for character in strings.utf8 {
     // for example A will converted to 65
     var utf8Value = character
}

I already read the guide but can't find how to convert Unicode code point that represented by integer to String. For example: converting 65 to A. I already tried to use the "\u"+utf8Value but it still failed.

Is there any way to do this?


回答1:


If you look at the enum definition for Character you can see the following initializer:

init(_ scalar: UnicodeScalar)

If we then look at the struct UnicodeScalar, we see this initializer:

init(_ v: UInt32)

We can put them together, and we get a whole character

Character(UnicodeScalar(65))

and if we want it in a string, it's just another initializer away...

  1> String(Character(UnicodeScalar(65)))
$R1: String = "A"

Or (although I can't figure out why this one works) you can do

String(UnicodeScalar(65))


来源:https://stackoverflow.com/questions/24107868/how-can-i-get-the-unicode-codepoint-represented-by-an-integer-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!