Last active
July 24, 2019 03:52
-
-
Save zackdotcomputer/0fa90de414f3bd066be96c4619505ebc to your computer and use it in GitHub Desktop.
Swift Character-is-emoji checker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Character { | |
/// An approximation of a spec-compatible "is this an emoji" check for the character. | |
/// Will recognize standard, flag, composite, tag emoji, and keycap emoji. | |
/// Unfortunately, will return true for "text presented" and malformed emoji too, | |
/// because I didn't do the whole CFG from Unicode. | |
var isEmoji: Bool { | |
// Empty character returns false | |
guard let first = self.unicodeScalars.first else { | |
return false | |
} | |
// 0-9, #, and * can be turned into emoji with the "emoji presentation" suffix | |
if first == "#" || first == "*" || (first >= "0" && first <= "9") { | |
let rest = self.unicodeScalars.dropFirst() | |
let emojiPresentationSuffix = [Unicode.Scalar(UInt32(0xFE0F))!, Unicode.Scalar(UInt32(0x20E3))!] | |
return rest.starts(with: emojiPresentationSuffix) | |
} | |
// All other emoji | |
return first.properties.isEmojiModifierBase || first.properties.isEmojiPresentation | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment