如何在Swift中获取由整数表示的Unicode代码点? [英] How can I get the Unicode codepoint represented by an integer in Swift?

查看:111
本文介绍了如何在Swift中获取由整数表示的Unicode代码点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道如何将String转换为utf8格式

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
}

我已经阅读了指南,但是找不到如何将整数表示的Unicode代码点转换为String.例如:将65转换为A.我已经尝试使用"\ u" + utf8Value,但仍然失败.

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.

有什么办法吗?

推荐答案

如果查看Character的枚举定义,则可以看到以下初始化程序:

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

init(_ scalar: UnicodeScalar)

如果我们再看一下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))

这篇关于如何在Swift中获取由整数表示的Unicode代码点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆