Search code examples
iosswiftuitextchecker

Disallow words less than 3 characters


In the Swift code below, the user chooses a word and types it into a text box, now how to disallow the words entered if less than 3 characters in length?

func isReal (word: String) -> Bool {
    //return true
    let checker = UITextChecker()
    let range = NSMakeRange(0, word.utf16.count)
    let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")
    return misspelledRange.location == NSNotFound
}

Solution

  • You can just add an if to check if the word has more than 3 characters:

    func isReal (word: String) -> Bool {
        if word.characters.count >= 3 {
            //return true
            let checker = UITextChecker()
            let range = NSMakeRange(0, word.utf16.count)
            let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")
            return misspelledRange.location == NSNotFound
        } else {
            return false
        }
    }
    

    This way, if word is shorter than 3 characters, it will return false, otherwise, it will test against the UITextChecker() and then return true or false respectively

    EDIT: Alternative using guard:

    func isReal (word: String) -> Bool {
        guard word.characters.count >= 3 else {
            return false
        }
    
        //return true
        let checker = UITextChecker()
        let range = NSMakeRange(0, word.utf16.count)
        let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")
        return misspelledRange.location == NSNotFound
    }
    

    If the guard statement is not met (being word.characters.count < 3), the function will automatically return false