2

I'm looking for a way to take a String and extract Emoji characters. I know that Emojis are part of Unicode so I need to remove a certain subset of Unicode characters. I don't really know where to start.

Farnabaz
  • 4,030
  • 1
  • 22
  • 42
shakked
  • 783
  • 8
  • 24

1 Answers1

16

The Set of Emoji characters

First of all we need a Set containing the unicode values representing the emoji.

Disclaimer

For this answer I am using the range of Emoticons (1F601-1F64F) and Dingbats (2702-27B0) to show you the solution. However keep in mind that you should add further ranges depending on your needs.

Extending Character

Now we need a way to calculate the Unicode Scalar Code Point of a Character. For this I am using the solution provided here.

extension Character {
    private var unicodeScalarCodePoint: Int {
        let characterString = String(self)
        let scalars = characterString.unicodeScalars
        return Int(scalars[scalars.startIndex].value)
    }
}

Extending String

This extension does allow you to extract the emoji characters from a String.

extension String {
    var emojis:[Character] {
        let emojiRanges = [0x1F601...0x1F64F, 0x2702...0x27B0]
        let emojiSet = Set(emojiRanges.flatten())
        return self.characters.filter { emojiSet.contains($0.unicodeScalarCodePoint) }
    }
}

Testing

let sentence = " hello world "
sentence.emojis // ["", ""]
Community
  • 1
  • 1
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148