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.

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()

Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips