我正在尝试将十六进制的表情符号转换成文本,我找到了一些在线代码可以实现此功能,但只能在Objective C中运行,如何使用Swift实现相同的功能?
这是一个“纯Swift”方法,不使用Foundation库:
let smiley = ""
let uni = smiley.unicodeScalars // Unicode scalar values of the string
let unicode = uni[uni.startIndex].value // First element as an UInt32
print(String(unicode, radix: 16, uppercase: true))
// Output: 1F60A
请注意,Swift中的Character
表示一个“Unicode字形群集”(与Swift博客中的Swift 2中的字符串进行比较),它可以由多个“Unicode标量值”组成。以@TomSawyer评论下面的示例为例:
let zero = "0️⃣"
let uni = zero.unicodeScalars // Unicode scalar values of the string
let unicodes = uni.map { $0.value }
print(unicodes.map { String($0, radix: 16, uppercase: true) } )
// Output: ["30", "FE0F", "20E3"]
extension String {
func decode() -> String {
let data = self.data(using: .utf8)!
return String(data: data, encoding: .nonLossyASCII) ?? self
}
func encode() -> String {
let data = self.data(using: .nonLossyASCII, allowLossyConversion: true)!
return String(data: data, encoding: .utf8)!
}
}
示例:
结果: \ud83d\ude0d
结果:
import Foundation
var smiley = ""
var data: NSData = smiley.dataUsingEncoding(NSUTF32LittleEndianStringEncoding, allowLossyConversion: false)!
var unicode:UInt32 = UInt32()
data.getBytes(&unicode)
// println(unicode) // Prints the decimal value
println(NSString(format:"%2X", unicode)) // Print the hex value of the smiley
0️⃣
由三个 Unicode 代码点组成:U+0030(字符“0”),后跟 U+FE0F(VARIATION SELECTOR-16)和 U+20E3(COMBINING ENCLOSING KEYCAP)- 您认为正确的输出应该是什么? - Martin R❤️
甚至不是一个单独的字符,它是由字符"", "❤️", "", ""
组成的字符串。 - Martin R