Logo for tanaschita.com

How to detect the language of a text with the Natural Language framework in Swift

Learn to use the language recognizer of the Natural Language framework.

01 May 2023 · 2 min read

If we need to detect a language of some text in an iOS application, for example some user input, the Natural Language framework comes in handy. It provides the NLLanguageRecognizer type which we can use for that purpose.

Sponsorship logo
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

When using the language recognizer, we get the most likely language for a piece of text or a set of possible languages with their probabilities.

func language(for text: String) -> NLLanguage? {
let recognizer = NLLanguageRecognizer()
recognizer.processString(text)
return recognizer.dominantLanguage
}

We can then use the optained language to switch over the languages:

guard let language = language(for: text) else { return }
switch language {
case .english:
...
}

To get a set of languages with their probabilities, we can use the languageHypotheses(withMaximum:) method:

func languages(for text: String) -> [NLLanguage: Double] {
let recognizer = NLLanguageRecognizer()
recognizer.processString(text)
return recognizer.languageHypotheses(withMaximum: 5)
}

To process another text with the same recognizer, we need to call its reset() method to return it to its initial state:

recognizer.reset()
Sponsorship logo
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

machine learning

swift

ios

Quick tip on how to split text into words with the Natural Language framework in Swift.

Learn how the tokenizer of the Natural Language framework works.

19 Jun 2023 · 2 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum