Convert emoji to hex value using Swift

我的梦境 提交于 2019-12-20 05:02:07

问题


I'm trying to convert emojis in hex values, I found some code online to do it but it's only working using Objective C, how to do the same with Swift?


回答1:


This is a "pure Swift" method, without using 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

Note that a Swift Character represents a "Unicode grapheme cluster" (compare Strings in Swift 2 from the Swift blog) which can consist of several "Unicode scalar values". Taking the example from @TomSawyer's comment below:

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"]



回答2:


If some one trying to found a way to convert Emoji To Unicode string

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)!
  }
}

Example:

  1. "😍".encode()

RESULT: \ud83d\ude0d

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

RESULT: 😍




回答3:


It works similarly but pay attention when you're printing it:

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


来源:https://stackoverflow.com/questions/27277856/convert-emoji-to-hex-value-using-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!