如何在Swift中将Unicode字符转换为Int

如何在Swift中将Unicode字符转换为Int

问题描述:

用户询问以下问题以我的一个答案


我有一个unicode字符 \ u {0D85} 。如何从中获取 Int 值?

我打算去将它们引用到另一个Stack Overflow Q& A但我找不到一个。这些是指转换另一个方向:

I was going to refer them to another Stack Overflow Q&A but I couldn't find one. These refer to converting the other direction:

  • How to convert an Int to a Character in Swift
  • How can I get the Unicode codepoint represented by an integer in Swift?

这些似乎是在询问如何将字符串形式的数字转换为实际的 Int (如将1转换为 1 )。

And these seem to be asking how to convert a number in string form to an actual Int (as in converting "1" to 1).

  • Convert Character to Int in Swift 2.0
  • Convert Character to Int in Swift

而不是尝试将我的答案放在co中请问提问者,我将在下面提供答案。 \ u {0D85} 的类型有点不清楚,但我将介绍各种可能性。

Rather than try to fit my answer in a comment to the asker, I am going to provide an answer below. The Type of \u{0D85} is somewhat unclear but I will cover the various possibilities.

Hex到Int

如果您从 \ u {0D85}开始并且您知道Unicode字符的十六进制值,那么您也可以使用以下格式编写它,因为它已经是 Int 。 / p>

If you are starting with \u{0D85} and you know the hex value of the Unicode character, then you might as well write it in the following format because it is an Int already.

let myInt = 0x0D85                          // Int: 3461

字符串到Int

我假设你有 \u {0D85}(引号中),默认情况下为 String 。由于它是 String ,因此您不能确定您只有一个 Int 值一般情况。

I assume, though, that you have "\u{0D85}" (in quotes), which makes it a String by default. And since it is a String, you can't be certain that you will only have a single Int value for the general case.

let myString = "\u{0D85}"

for element in myString.unicodeScalars {
    let myInt = element.value               // UInt32: 3461
}

我本可以使用 myString.utf16 让myInt = Int(元素),但我发现它更容易当有可能出现像表情符号这样的东西时,处理Unicode标量值(UTF-32)。 (有关详细信息,请参阅此答案。)

I could have also used myString.utf16 and let myInt = Int(element), but I find it easier to deal with Unicode scalar values (UTF-32) when there is a possibility of things like emoji. (See this answer for more details.)

字符到Int

Swift 字符,这是扩展字形集群,没有 utf16 unicodeScalars 属性,所以如果你从字符开始然后首先将其转换为 String ,然后按照上面 String to Int 部分中的说明进行操作。

Swift Character, which is an extended grapheme cluster, does not have a utf16 or unicodeScalars property, so if you are starting with Character then convert it to a String first and then follow the directions in the String to Int section above.

let myChar: Character = "\u{0D85}"
let myString = String(myChar)