0

Given the following:

                       ["name":"CAT FACE WITH WRY SMILE", "utf":"1F63C"],
                       ["name":"KISSING CAT FACE WITH CLOSED EYES", "utf":"1F63D"],
                       ["name":"POUTING CAT FACE", "utf":"1F63E"],
                       ["name":"CRYING CAT FACE", "utf":"1F63F"]

How do I convert the utf part into an emoji, e.g. , in a scalable, performant way (there are thousands of these)

I tried something like:

String(utf8String: utf.cString(using: String.Encoding.utf8)

but it doesn't work

user11145365
  • 184
  • 9

1 Answers1

2

You can convert the string into a hexadecimal integer, and then into a UnicodeScalar.

Here's how you can convert a basic string:

let str = "1F63C"
let result = UnicodeScalar(Int(str, radix: 16)!)!
print(result)

Prints:


And your more complicated example:

let arr = [
    ["name":"CAT FACE WITH WRY SMILE", "utf":"1F63C"],
    ["name":"KISSING CAT FACE WITH CLOSED EYES", "utf":"1F63D"],
    ["name":"POUTING CAT FACE", "utf":"1F63E"],
    ["name":"CRYING CAT FACE", "utf":"1F63F"]
]

for element in arr {
    let result = UnicodeScalar(Int(element["utf"]!, radix: 16)!)!
    print("\(element["name"]!): \(result)")
}

Prints:

CAT FACE WITH WRY SMILE: 
KISSING CAT FACE WITH CLOSED EYES: 
POUTING CAT FACE: 
CRYING CAT FACE: 

Note: there are a lot of force-unwraps. Ideally you would handle these in your own sensible way.

George
  • 25,988
  • 10
  • 79
  • 133