【发布时间】:2015-02-01 09:04:33
【问题描述】:
我正在尝试将表情符号转换为十六进制值,我发现 some code online 可以做到这一点,但它只适用于 Objective C,如何用 Swift 做同样的事情?
【问题讨论】:
我正在尝试将表情符号转换为十六进制值,我发现 some code online 可以做到这一点,但它只适用于 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 博客的 Strings in 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"]
【讨论】:
0️⃣ 由三个 Unicode 代码点组成:U+0030(字符“0”),然后是 U+FE0F(VARIATION SELECTOR-16)和 U+20E3(组合封装) KEYCAP) – 你认为正确的输出应该是什么?
?❤️?? 甚至不是单个字符,它是由字符"?", "❤️", "?", "?" 组成的String。
如果有人试图找到一种方法将 Emoji 转换为 Unicode 字符串
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
【讨论】: