Swift 5 isEmoji 方法 returns 对数字正确吗?
Swift 5 isEmoji method returns true for a number?
就像下面的例子 isEmoji 方法 returns true 对于 number :
let scalars: [Unicode.Scalar] = ["", "+", "1"]
for s in scalars {
print(s, "-->", s.properties.isEmoji)
}
// --> true
// + --> false
// 1 --> true... wait what?
但是 为什么 和 如何 确定我示例中的最后一个案例。
遇到这个问题后我稍微搜索了一下,在Apple's documentation中找到了答案。我分享给你,以免你以后浪费宝贵的时间:
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.
解决方案
所以你可以像下面这样检查:
let scalars: [Unicode.Scalar] = ["", "+", "1"]
for s in scalars {
print(s, "-->", (s.properties.isEmoji && s.properties.isEmojiPresentation))
}
// --> true
// + --> false
// 1 --> false
就像下面的例子 isEmoji 方法 returns true 对于 number :
let scalars: [Unicode.Scalar] = ["", "+", "1"]
for s in scalars {
print(s, "-->", s.properties.isEmoji)
}
// --> true
// + --> false
// 1 --> true... wait what?
但是 为什么 和 如何 确定我示例中的最后一个案例。
遇到这个问题后我稍微搜索了一下,在Apple's documentation中找到了答案。我分享给你,以免你以后浪费宝贵的时间:
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.
解决方案
所以你可以像下面这样检查:
let scalars: [Unicode.Scalar] = ["", "+", "1"]
for s in scalars {
print(s, "-->", (s.properties.isEmoji && s.properties.isEmojiPresentation))
}
// --> true
// + --> false
// 1 --> false