FREE: Follow my new 100 Days of Swift challenge! >>

How to detect the dominant language of a text string

Paul Hudson       @twostraws

The NSLinguisticTagger class has dedicated code to help you identify the dominant language of a text string. Before I show you the code, there are three important provisos:

  1. It detects the dominant language, which means if you provide it with text that contains more than one language it will return whichever one appears most often.
  2. If you give it text where no identification can be made, e.g. some numbers or an empty string, it will return nil.
  3. It is extraordinarily fast – you can feed it thousands of article-length strings a second and it will fly through them.

Here’s an example to help you get started:

let text = "Ceci n'est pas une pipe"

if let language = NSLinguisticTagger.dominantLanguage(for: text) {
    print(language)
} else {
    print("Unknown language")
}

When that code runs it will print “fr”, because the dominant language in the text is French.

Sponsored You’re already busy updating your app for Swift 4.2 and iOS 12, so why not let Instabug help you find and fix bugs? Add just two lines of code to your project and receive comprehensive reports with all the feedback you need to ship a world-class app – click here to learn more!

Available from iOS 11.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>