我有一个问题找不到解决方案。
我有一个字符串变量保存unicode“1f44d”,我想将其转换为unicode字符????。
通常人们会做这样的事情:
println("\u{1f44d}") // ????
我的意思是:
let charAsString = "1f44d" // code in variable
println("\u{\(charAsString)}") // not working
我尝试过其他几种方法,但不知何故,这个魔法背后的工作原理对我来说仍然是隐藏的。
人们应该想象 charAsString 的值来自 API 调用或来自另一个对象。
一种可能的解决方案(“内联”解释):
let charAsString = "1f44d"
// Convert hex string to numeric value first:
var charCode : UInt32 = 0
let scanner = NSScanner(string: charAsString)
if scanner.scanHexInt(&charCode) {
// Create string from Unicode code point:
let str = String(UnicodeScalar(charCode))
println(str) // ????
} else {
println("invalid input")
}
稍微简单一些Swift 2:
let charAsString = "1f44d"
// Convert hex string to numeric value first:
if let charCode = UInt32(charAsString, radix: 16) {
// Create string from Unicode code point:
let str = String(UnicodeScalar(charCode))
print(str) // ????
} else {
print("invalid input")
}
另请注意,并非所有代码点都是有效的 Unicode 标量,
比较在 Swift 中验证 Unicode 代码点 https://stackoverflow.com/questions/31693419/validate-unicode-code-point-in-swift.
更新为Swift 3:
public init?(_ v: UInt32)
现在是一个可失败的初始化程序UnicodeScalar
并检查是否
给定的数字输入是有效的 Unicode 标量值:
let charAsString = "1f44d"
// Convert hex string to numeric value first:
if let charCode = UInt32(charAsString, radix: 16),
let unicode = UnicodeScalar(charCode) {
// Create string from Unicode code point:
let str = String(unicode)
print(str) // ????
} else {
print("invalid input")
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)