在Swift中通过多个关键字过滤对象



我试图根据随机顺序的多个键(姓名,姓氏,职位,员工ID)过滤对象。例如,对于员工(John, Newman, Accountant, 1234),我想根据以下搜索找到他:

约翰1234年
  • 纽曼会计等。

我在一个类似的问题上找到了一个很好的解决方案->在这里,但我不能评论,因为口碑不好。

func getSearchResults(_ filterKey: String) {
let components = filterKey.components(separatedBy: " ")
self.filteredContacts = contacts.filter { contact -> Bool in
for string in components {
if contact.givenName != string && contact.familyName != string && contact.organizationName != string {
return false
}
}
return true
}
}

我这样修改了代码:

func getSearchResults(_ filterKey: String) {
let components = filterKey.components(separatedBy: " ")
self.filteredContacts = contacts.filter { contact -> Bool in
for string in components {
if !(contact.givenName.range(of: string, options: [.caseInsensitive, .diacriticInsensitive]) != nil) && contact.familyName.range(of: string, options: [.caseInsensitive, .diacriticInsensitive]) != nil) && contact.organizationName.range(of: string, options: [.caseInsensitive, .diacriticInsensitive]) != nil) {
return false
}
}
return true
}
}

除了一个细节外,它工作得非常好-只要我在第一个单词后按空格键,搜索结果就是空的,当我开始键入第二个单词时,结果就会如预期的那样返回。

有什么方法可以防止这种情况发生吗?我想看看"约翰"的搜索结果。即使当前搜索词是"John">

在分割字符串

之前先剪掉前后空白字符
let components = filterKey.trimmingCharacters(in: .whitespaces).components(separatedBy: " ")

或修改循环

for string in components where !string.isEmpty { ...

最新更新