Search code examples
swiftlocalizationspell-checkinghebrewspelling

Spellchecking with UITextChecker for hebrew text in Swift 5


I am getting true returned for any Hebrew text, regardless of the text containing any real words:

func wordIsSpelledCorrect(word: String) -> Bool {
  let checker = UITextChecker()
  let range = NSRange(location: 0, length: word.count)
  let wordRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "he")

  return wordRange.location == NSNotFound
}
// wordIsSpelledCorrect("שלום") // which is Hebrew for "peace" returns true
// but
// wordIsSpelledCorrect("םולש") // which is not a real word, also returns true

I have the Hebrew dictionary installed on my device—and I've tried both with and without Hebrew set as the "iPhone Language" in Settings > Language & Region. Does anyone know if the Hebrew language just isn't supported by UITextChecker? If so, is always returning true the expected behavior for unsupported languages?

I have this working fine for English. If UITextChecker is a bust for Hebrew, any ideas of other ways I might solve this? I'd prefer another solution anyway since my app is universal and UIKit doesn't work on macOS.

[Update 1]

I spent some time investigating accessing the language dictionary for macOS and turned up nothing. I don't see how this is a mobile-only need. For example, isn't this implemented by Apple in Pages and their own Dictionary App? I would guess my next step would be to start investigating multi-language dictionary API's, but it seems really inefficient to make a call for something that I know is sitting right there on the system. Any ideas or direction would be much appreciated.

[Update 2]

According to the answers here the API I was looking for doesn't exist, so I'll have to put my Universal App on hold. But going back to the code above, which works beautifully in all the languages I've tried besides Hebrew, can anyone help me get Hebrew working for iOS?

[Update 3]

For completeness, here's the code that is working for English, French, Spanish, etc:

func wordIsSpelledCorrect(word: String) -> Bool {
    if let language = NLLanguageRecognizer.dominantLanguage(for: word) {
        let checker = UITextChecker()
        let range = NSRange(location: 0, length: word.count)
        let wordRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: language.rawValue)
        return wordRange.location == NSNotFound
    } else {
        return false
    }
}

Solution

  • Check that the language is in the UITextChecker.availableLanguages. Otherwise UITextChecker will find no errors in spelling.