Using Emojis with Swift 4

Somewhere around this time last year, I found something really interesting, which was that Emoji characters were handled differently by Swift. While you ask what do you mean by differently, the answer is, You might have used emoji's in some or the other chat applications, whatsapp, messages, facebook, etc. These emojis got the ability to have a skin color based off the Fitzpatrick scale. So you could represent an emoji in one of those skin tones. However, when you work with strings that contained emojis, it was interesting as strings handling unicode thought of a unicode character as more than 1 character.

The Issue

Let's look at the problem, the emoji 👍 is the base emoji with the skin color yellow. However, this can then be changed to a particular skin tone by adding the skin tone as a character. It is similar to lot of unicode languages where two characters together form a new character. So if you used "👍" + "🏼" then you get the medium light skinned thumbs-up as "👍🏼". If you were to get the length of this string, it would return a string length of 2. This is incorrect because this is a single character and the skin-tone should not be considered as a character. The reason being is you were to perform string functions like slicing or reversing, etc the results would be incorrect.

What did I do?

I posted a tweet and there was a bit of traction, other developers found that interesting. The Emoji of a woman and man with a heart was actually 3 characters, that were exactly as per the description, the woman, the man and the heart. You could create the emoji by simply adding the characters. "👩" + "❤️" + "👨" = "💑", and the length of this should be a single character but would display as 3. I filed a bug with Apple (ID: 27917853) which explained that this behaviour is incorrect.

How do I know?

The reasoning above explained that it was a problem and the code below was used to test this.

let str = "Good Coffee 👍🏻"
for character in str.characters {
print(character)
}

The resulting output was
G
o
o
d
 
C
o
f
f
e
e
 
👍
🏻

But what should have been the output was
G
o
o
d
 
C
o
f
f
e
e
 
👍🏻

Is it fixed in Swift 4?

Yes the good thing is that this has been fixed in Swift 4. The better part is that while Python 3 has some interesting unicode handling, I believe Swift4 is the only release that manages unicode the right way.

So you can now use the same in your code as
let thumbsup = "👍"


let paleskintone = "\u{1F3FB}"
let mediumlightskintone = "\u{1F3FC}"
let mediumskintone = "\u{1F3FD}"
let brownskintone = "\u{1F3FE}"
let darkskintone = "\u{1F3FF}"


print(thumbsup + paleskintone)
print(thumbsup + mediumlightskintone)
print(thumbsup + mediumskintone)
print(thumbsup + brownskintone)
print(thumbsup + darkskintone)






Comments

Popular Posts