Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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