How to show emojis with Strings in Swift using Unicode hexadecimal values (UTF-16)

Mehdi S
3 min readJan 3, 2020

--

[Face_With_Tears_Of_Joy_Emoji]

I’ll focus on doing this the “fashion” way by using hexadecimal String that represent Unicode values of our Emojis.

GETTING THE EMOJI CODE RANGES

(this part is skippable if you already know which Emoji you want to print out)

Luckily for us, Unicode as a standard is well documented so are the emoji range we seek.

Heading toward the official unicode website on the Emoji section we are greeted by some data about emojis, usage and such, what’s interesting here is their data files, where you can find all the sequences reserved in Unicode standard for Emojis.

Heading over https://unicode.org/Public/emoji/15.0/

(bear in mind that a newer emoji set can be available when you are reading this)

It’s a bit less interesting website, visually-wise, don’t let this discourage you.

By clicking on the emoji-sequences.txt file you can see, all emoji ranges with their exact Hex code, it must be read “FROM_HEX..TO_HEX”.

FROM_HEX..TO_HEX

We have now plenty of emojis to play with ! Let’s dive into code shall we.

PRINT EMOJI PROGRAMATICALLY IN SWIFT

So you want to be part of the cool kid, uh ?

Let’s start from the Hex “0x1F602” :

let c = 0x1F602
print(String(UnicodeScalar(c)!))

On line 2, we transform our Hex String into an UInt32 with the method UnicodeScalar(), and cast the result to print a String representation of the emoji.

Here we have a “😂” printed out in our console, yay! , and it’s not over yet !

Also, it is very important to understand what UnicodeScalar() method do. It convert our Hexadecimal into a 32 Bit Integer representation of our Emoji in the Unicode Table by converting it into an UnicodeScalar Type, which can then be understood by the String() method to correctly present it as a character and not as a simple Int :

And if you’re wondering why we searched for ranges on the Unicode website, it’s because it works with ranges of hexadecimals too !

let emojiRanges = [
0x1F600…0x1F636,
0x1F645…0x1F64F,
0x1F910…0x1F91F,
0x1F30D…0x1F52D
]

for range in emojiRanges {
for i in range {
let c = UnicodeScalar(i)
data.append(c)
}
}

Congrats ! your data Array variable is now full of Integers that can be print out with

String(UnicodeScalar(data[i])!)

by looping inside of it !

Thanks for reading, Thanks for the Clap !

To🕑✌protect😷😷😷the world🌎🌎🌐🌐🌐from devastation😭😭😭😩😫😫To unite all people👫👬👭👯within our nation 🏴󠁧󠁢󠁥󠁮󠁧󠁿 To denounce😝😛😝😝the evils😈👿👿👹👹👺of truth🤥🤥😇😇 and love❤️🧡💛💚💙💜🤎💓💞💕❣️🤍🖤💗💖💘💝💟To extend our reach🤲👐🙌✋🤚🖐️🖖👋 to the stars⭐🌟✨✨🌟 above👆👆 Jessie💃👠👠🩱👀👄💄James🕺💅👨‍❤️‍💋‍👨👞👞👅👅Team Rocket 🚀🚀 🚀 blast 🎆🎇💥💥💥 off at the speed of light☀️☀️🌟✨⭐ Surrender👏🙏🙏now or prepare to fight👊✊👊👊Meowth😺😸😾😿🙀😽😼😻😹thats right👍👍👌👌👌💯💯

--

--

Mehdi S

iOS Developer @ LVMH Paris — Currently searching what will be “the next big thing”