I've cobbled this class together, which is a mixture of real and pseudocode. I would create a singleton class for first names and last names. See comments in code for details. This isn't the whole thing, but it should solve most of your problem.
Update
Tweaked the cleanUpString
method with a switch statement.
Update 2
Added this to take care of whatever UITextChecker
doesn't...
return UIReferenceLibraryViewController.dictionaryHasDefinition(forTerm: self)
Wherever you're getting your OCR text from, you'd use it like this:
let stringParser = StringParser()
let cleanedUpText = stringParser.cleanUpString(yourOCRText)
Here's the class:
import UIKit // need this so UITextChecker will work
import Foundation
class StringParser: NSObject {
// TODO: You'll need to create a singleton class for your first and last names
// https://krakendev.io/blog/the-right-way-to-write-a-singleton
func cleanUpString(_ inputString: String) -> String {
// chuck stuff separated by a space into an array as an invdividual string
let inputStringArray = inputString.characters.split(separator: " ").map(String.init)
var outputArray = [String]()
for word in inputStringArray {
// Switch to check if word satisfies any of the desired conditions...if so, chuck in outputArray
switch word {
case _ where word.isRealWord():
outputArray.append(word)
break
case _ where word.isFirstName():
outputArray.append(word.capitalized)
break
case _ where word.isLastName():
outputArray.append(word.capitalized)
break
default:
break
}
}
// reassemble the cleaned up words into an output array and return it as a single string
return outputArray.joined(separator: " ")
}
}
extension String {
func isFirstName() -> Bool {
let firstNameArray = ["Andrew", "Sharon"] // FIXME: this should be your singleton
return firstNameArray.contains(self.capitalized)
}
func isLastName() -> Bool {
let lastNameArray = ["Webster", "Hazelwood"] // FIXME: this should be your singleton
return lastNameArray.contains(self.capitalized)
}
func isRealWord() -> Bool {
// adapted from https://www.hackingwithswift.com/example-code/uikit/how-to-check-a-string-is-spelled-correctly-using-uitextchecker
let checker = UITextChecker()
let range = NSRange(location: 0, length: self.utf16.count)
let misspelledRange = checker.rangeOfMisspelledWord(in: self, range: range, startingAt: 0, wrap: false, language: "en")
if misspelledRange.location == NSNotFound {
// cleans up what UITextChecker misses
return UIReferenceLibraryViewController.dictionaryHasDefinition(forTerm: self) // returns yes if there's a definition for it
}
return false
}
}