使用Swift将表情符号转换为十六进制值

Arm*_*let 1 hex emoji swift

我正在尝试使用十六进制值转换表情符号,我在网上发现了一些代码,但它只能使用Objective C,如何使用Swift做同样的事情?

Mar*_*n R 9

这是一个"纯粹的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)


Gok*_*kul 6

如果有人试图找到一种将表情符号转换为 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)

例子:

  1. "".encode()

结果: \ud83d\ude0d

  1. "\ud83d\ude0d".decode()

结果: