首页 > 解决方案 > 将 Unicode 中的结果推迟到 Swift 中的字符串

问题描述

我正在使用此向下代码将我的String值转换为unicodeScalars,例如,如果我将"A"作为输入,我将得到65作为输出,现在我知道65A的数量,那么我想给65以再次接收A,但它给了e,我确信我将一些主题混合在一起并且还遗漏了一些东西,需要一些帮助来理解为什么这是不同的以及如何使用"\u{???}"来返回我的字符串,谢谢

let string: String = "A"
let UInt32Value: UInt32 = string.unicodeScalars[string.startIndex].value
print(UInt32Value) // 65


let newString = "\u{65}"
print(newString) // e

ps:我知道有使用 unicodescalar 来取回字符串的官方方法,但我对 "\u{?????}" 感兴趣

标签: swiftstringunicodescalar

解决方案


尝试转换如下

let ans =  String(UnicodeScalar(UInt8(65)))
print(ans)

我认为问题是,您正在转换 (A) 字符串 -> unicodescalar -> uint

并且必须转换 (65) uint -> unicodescalar -> string 以获得原始值


推荐阅读