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.
Asked
Active
Viewed 2,596 times
2
-
Read about Swift strings https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html – Jean-Baptiste Yunès Jan 30 '16 at 19:42
-
1What is your goal I don't understand your question... – Tom el Safadi Jan 30 '16 at 19:43
1 Answers
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