您可以添加一个if
来检查单词是否超过 3 个字符:
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
}
}
这样,如果word
小于 3 个字符,则返回,否则,将分别false
测试UITextChecker()
然后返回true
orfalse
编辑:替代使用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
}
如果guard
不满足语句(word.characters.count < 3),函数会自动返回false