- Published on
- 1 min read
> How to get the name of an emoji in Swift
If you find yourself building an emoji picker or maybe a reactions UI, it is likely that you'll need to display the names of each emoji. Many solutions to this involve maintaining a dictionary between the emoji and their names, but there is a way to get the system names for each emoji using kCFStringTransformToUnicodeName. The example below uses the CFStringTransform API to obtain the name of the emoji in the input string. It then parses the human readable name from the output.
The transform returns the format \N{AIRPLANE} for each emoji that is present in the input string. In this example, we assume that only one emoji is present, but this could easily be adapted to support multiple emoji by replacing the string split with a map operation.
func getName(for emoji: String) -> String? {
let string = NSMutableString(string: String(emoji))
var range = CFRangeMake(0, CFStringGetLength(string))
CFStringTransform(string, &range, kCFStringTransformToUnicodeName, false)
guard let firstName = string.components(separatedBy: "\\N").first else {
return nil
}
return firstName.trimmingPrefix("\\N")
.trimmingCharacters(in: .punctuationCharacters)
.capitalized
}
// Continue_Learning
Generating a Random Emoji in Swift
How to generate random emoji characters in Swift using Unicode scalar ranges.
How to Replace Characters in a String in Swift
Learn multiple approaches to replace characters and substrings in Swift strings, from simple replacements to pattern-based transformations.
Understanding the "some" Keyword in Swift and SwiftUI
Learn what the "some" keyword means in Swift, how opaque return types work, and why SwiftUI uses "some View" everywhere.
// Stay Updated
Get notified when I publish new tutorials on Swift, SwiftUI, and iOS development. No spam, unsubscribe anytime.