I believe this post has the answer you're looking for but NOTE it will ignore proper nouns and other words that should be capitalized. You might be able to get what you're looking for by using this as well as UITextChecker
. It's a bit old and doesn't have any answers updated for newer versions of Swift, so I went ahead and updated the syntax from this answer:
extension String {
func toUppercaseAtSentenceBoundary() -> String {
var result = ""
self.uppercased().enumerateSubstrings(in: self.startIndex..<self.endIndex, options: .bySentences) { (sub, _, _, _) in
result += String(sub!.prefix(1))
result += String(sub!.dropFirst(1)).lowercased()
}
return result as String
}
}
// Example usage
var str = "this Is my String."
print(str.toUppercaseAtSentenceBoundary())
For correcting spelling errors
The UITextChecker class is something you might also want to look into using if you want to correct any misspellings in your text as well (you did mention autocorrect so I figured I'd add this in).
NSHipster has a nice tutorial on how to use it. Here's the code example from their tutorial.
import UIKit
let str = "hipstar"
let textChecker = UITextChecker()
let misspelledRange =
textChecker.rangeOfMisspelledWord(in: str,
range: NSRange(0..<str.utf16.count),
startingAt: 0,
wrap: false,
language: "en_US")
if misspelledRange.location != NSNotFound,
let firstGuess = textChecker.guesses(forWordRange: misspelledRange,
in: str,
language: "en_US")?.first
{
print("First guess: \(firstGuess)") // First guess: hipster
} else {
print("Not found")
}
Getting the text to check:
If you're using a UITextField, implement the UITextFieldDelegate to check the spelling of the string when text field is finished editing, via the textFieldShouldEndEditing(_:)
method.
If you're using a UITextView, you can use the similar UITextViewDelegate methods to determine when to check and replace various words in the string.