我必须根据文章描述中的关键字(字符串)过滤文章数组。过滤 1500 多个元素的文章类型数组和每篇文章描述中的 2000 多个单词需要 2-3 秒。
我正在使用下面的代码;我也试过 predicate 但对我没用。
let searchResult = articlesList.filter {
let article = $0
let filterByName = article.title.lowercased().range(of: text.lowercased())
let filterByDescription = article.body.lowercased().range(of: (text.lowercased()))
if ((filterByName != nil) || filterByDescription != nil) {
if !articlesList.contains(article) {
articlesList.append(article)
}
}
else {
let index = articlesList.index(of: article)
if index != nil {
articlesList.remove(at: index!)
}
}
return false
}
我希望过滤时间最长为 0.3 秒。
最佳答案
这可能比 bit 快很多
let searchResult = articles.filter{ $0.title.range(of: text, options: .caseInsensitive) != nil
|| $0.body.range(of: text, options: .caseInsensitive) != nil }
关于arrays - Filter Custom Array时间优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54035122/