Why isEmoji Instance Property Returns true for numbers?
Asked Answered
G

1

3

Problem

Why isEmoji instance property returns true for numbers?

Check the example below:

let scalars: [Unicode.Scalar] = ["πŸ€“", "+", "1"]
for s in scalars {
    print(s, "-->", s.properties.isEmoji)
}

Results

// πŸ€“ --> true
// + --> false
// 1 --> true... 

wait what? 😦

But why? The question is how to use the isEmoji property for numbers in the right way.

Gobo answered 4/8, 2020 at 9:18 Comment(0)
G
6

What

If you're not familiar with the isEmoji instance property it's a boolean value indicating whether the scalar has an emoji presentation, and whether or not it is the default.

It's available under iOS 10.2+, iPadOS 10.2+, macOS 10.12.2+, Mac Catalyst 10.2+, tvOS 10.1+, watchOS 3.1.1+, visionOS 1.0+ Beta.

I did a little research after facing this issue and found the answer in Apple's documentation.

Why

The final result is true because the ASCII digits have non-default emoji presentations; some platforms render these with an alternate appearance.

Because of this behavior, testing isEmoji alone on a single scalar is insufficient to determine if a unit of text is rendered as an emoji; a correct test requires inspecting multiple scalars in a Character.

In addition to checking whether the base scalar has isEmoji == true, you must also check its default presentation (see isEmojiPresentation) and determine whether it is followed by a variation selector that would modify the presentation. This property corresponds to the β€œEmoji” property in the Unicode Standard.

Solution

So you can check like the line below:

let scalars: [Unicode.Scalar] = ["πŸ€“", "+", "1"]

for s in scalars {
    print(s, "-->", (s.properties.isEmoji && s.properties.isEmojiPresentation))
}

Final Results

// πŸ€“ --> true
// + --> false
// 1 --> false

πŸŽ‰

Gobo answered 4/8, 2020 at 9:18 Comment(5)
This won't work for "✈️" which returns true for isEmoji and false for isEmojiPresentation – Electrotonus
Won't work for those: ▢️3οΈβƒ£πŸŒΆ, too. – Erudition
Here's a nice working example from someone on GitHub: gist.github.com/krummler/879e1ce942893db3104783d1d0e67b34 – Beshore
Thank you for sharing but, not %100 works I guess, print("πŸ‘ŒπŸΏ".isSingleEmoji) this returns false on Playgrounds, but the expected result is true in the comment. – Gobo
The gist linked to in the comment above doesn't account for skin tone modifiers. add a check for isEmojiModifier in line 12 and that example will work – Sangsanger

© 2022 - 2024 β€” McMap. All rights reserved.