简体   繁体   中英

UITextChecker for Set of Strings - Swift 4.2

I currently have this Extension thanks to @Leo Dabus. It works perfectly for a single String , but how would I implement this same logic to an Set of Strings like var mySet = ["word", "notaword", "stillnotaword"] . In this example, I would want the function to only identify the first index as true (ie an English word).

extension String {
    public mutating func isEnglishWord() -> Bool {
        return UITextChecker().rangeOfMisspelledWord(in: self, range: NSRange(location: 0, length: utf16.count), startingAt: 0, wrap: false, language: "en_US").location == NSNotFound
    }
}

var myString = "word"

myString.isEnglishWord()
let words = ["word", "notaword", "stillnotaword"]

let validWords = words.filter { word -> Bool in
    return word.isEnglishWord()
}

let wordsArray : NSArray = NSArray(array: words)
let validWordsIndexes = wordsArray.indexesOfObjects { (word, index, _) -> Bool in
    return (word as! String).isEnglishWord()
}

print(validWords)
print(validWordsIndexes)

extension String {
    public func isEnglishWord() -> Bool {
        return UITextChecker().rangeOfMisspelledWord(in: self, range: NSRange(location: 0, length: utf16.count), startingAt: 0, wrap: false, language: "en_US").location == NSNotFound
    }
}

I have added the code to print valid words and indexes of valid words. You can choose which ever suits you. Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM