0

我目前有这个Extension感谢@Leo Dabus。它适用于单个String,但我将如何将相同的逻辑实现到一个类似Set的。在此示例中,我希望该函数仅将第一个标识为(即英文单词)。Stringsvar mySet = ["word", "notaword", "stillnotaword"]indextrue

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()
4

1 回答 1

0
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
    }
}

我添加了代码来打印有效词和有效词的索引。您可以选择适合您的。谢谢

于 2019-03-11T05:44:02.037 回答