这是一个"纯粹的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
Run Code Online (Sandbox Code Playgroud)
请注意,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"]
Run Code Online (Sandbox Code Playgroud)
如果有人试图找到一种将表情符号转换为 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)!
}
}
Run Code Online (Sandbox Code Playgroud)
例子:
结果: \ud83d\ude0d
结果:
归档时间: |
|
查看次数: |
3360 次 |
最近记录: |