Skip to content

Instantly share code, notes, and snippets.

@mohdsanadzakirizvi
Created November 26, 2019 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohdsanadzakirizvi/b88b699a9fec147b91a0b9a4580a3f26 to your computer and use it in GitHub Desktop.
Save mohdsanadzakirizvi/b88b699a9fec147b91a0b9a4580a3f26 to your computer and use it in GitHub Desktop.
import UIKit
import NaturalLanguage
// Check and suggest the spelling of words in the text
let string = """
I started my schooling as the majority did in my area, at the local primarry school. I then
went to the local secondarry school and recieved grades in English, Maths, Phisics,
Biology, Geography, Art, Graphical Comunication and Philosophy of Religeon. I'll not
bore you with the 'A' levels and above.
"""
// find the dominant language of text
let dominantLanguage = NLLanguageRecognizer.dominantLanguage(for: string)
print(string+", has dominant language:\(dominantLanguage!.rawValue)")
// initialize UITextChecker, nsString, stringRange
let textChecker = UITextChecker()
let nsString = NSString(string: string)
let stringRange = NSRange(location: 0, length: nsString.length)
var offset = 0
repeat {
// find the range of misspelt word
let wordRange =
textChecker.rangeOfMisspelledWord(in: string,
range: stringRange,
startingAt: offset,
wrap: false,
language: dominantLanguage!.rawValue)
// check if the loop range exceeds the string length
guard wordRange.location != NSNotFound else {
break
}
// get the misspelt word
print(nsString.substring(with: wordRange))
// get some suggested words for the misspelt word
print(textChecker.guesses(forWordRange: wordRange, in: string, language: dominantLanguage!.rawValue))
// update the start index or offset
offset = wordRange.upperBound
} while true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment