With Swift 5, you can choose one of the following approaches in order to detect the language of a given string.
#1. Using NSLinguisticTagger
's dominantLanguage
property
Since iOS 11, NSLinguisticTagger
has a property called dominantLanguage
. dominantLanguage
has the following declaration:
var dominantLanguage: String? { get }
Returns the dominant language of the string set for the linguistic tagger.
The Playground sample code below show how to use dominantLanguage
in order to know the dominant language of a string:
import Foundation
let text = "あなたはそれを行うべきではありません。"
let tagger = NSLinguisticTagger(tagSchemes: [.language], options: 0)
tagger.string = text
let language = tagger.dominantLanguage
print(language) // Optional("ja")
#2. Using NSLinguisticTagger
's dominantLanguage(for:)
method
As an alternative, NSLinguisticTagger
has a convenience method called dominantLanguage(for:)
for creating a new linguistic tagger, setting its string
property and getting the dominantLanguage
property. dominantLanguage(for:)
has the following declaration:
class func dominantLanguage(for string: String) -> String?
Returns the dominant language for the specified string.
Usage:
import Foundation
let text = "Die Kleinen haben friedlich zusammen gespielt."
let language = NSLinguisticTagger.dominantLanguage(for: text)
print(language) // Optional("de")
#3. Using NLLanguageRecognizer
's dominantLanguage
property
Since iOS 12, NLLanguageRecognizer
has a property called dominantLanguage
. dominantLanguage
has the following declaration:
var dominantLanguage: NLLanguage? { get }
The most likely language for the processed text.
Here’s how to use dominantLanguage
to guess the dominant language of natural language text:
import NaturalLanguage
let string = "J'ai deux amours. Mon pays et Paris."
let recognizer = NLLanguageRecognizer()
recognizer.processString(string)
let language = recognizer.dominantLanguage
print(language?.rawValue) // Optional("fr")