给定一个列表:
let words = ["Apple", "the Banana", "Cherry"]
和一个字符串:
let string = "The Apple was eaten before the Banana"
是否可以很容易地获得数组中字符串中短语的列表?
例如,上述结果为:
let result = ["Apple", "the Banana"]
以下内容很接近,但只返回true或false:
let combinedResult = words.contains(where: string.contains)
您可以过滤您的数组,条件是它存在于字符串中,如下所示:
let words = ["Apple", "the Banana", "Cherry"]
let string = "The Apple was eaten before the Banana"
print(words.filter { string.contains($0) }) // ["Apple", "the Banana"]
对于我的用例,运行需要27秒
var words: [String] { Words.all.filter { self.contains($0) } }
而这需要1.5秒:
var words: [String] {
var words = [String]()
for word in self.components(separatedBy:" ") {
if WordDictionary.all[word] != nil {
words.append(word)
}
}
return words
}