Bru*_*s98 2 arrays struct swift
我想通过搜索栏过滤结构数组。我知道如何过滤字符串数组,但不幸的是我无法将它应用于结构数组。这是我已经做过的事情:
var BaseArray: [dataStruct] = []
var filteredArray: [dataStruct] = []
Run Code Online (Sandbox Code Playgroud)
BaseArray 是具有多个变量的结构数组。我的目标是过滤所有变量。有任何想法吗?
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == ""{
isSearching = false
view.endEditing(true)
tableView.reloadData()
}
else{
isSearching = true
filteredArray = BaseArray.filter { $0.name == searchText }
tableView.reloadData()
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您需要使用OR/union运算符将正结果合并到您的过滤数组中:||
所以你的过滤器函数看起来像这样:
filteredArray = BaseArray.filter {
$0.name == searchText
|| $0.anotherProperty == searchText
|| $0.yetAnotherProperty == searchText
}
Run Code Online (Sandbox Code Playgroud)
这样,如果name或anotherProperty或yetAnotherProperty等于您要搜索的文本,则将列出结果。
此外,您可能希望根据包含下一个的输入文本进行过滤,而不需要像示例中那样完全相等。在这种情况下,您的过滤器功能将变为:
filteredArray = BaseArray.filter {
$0.name.contains(searchText)
|| $0.anotherProperty.contains(searchText)
|| $0.yetAnotherProperty.contains(searchText)
}
Run Code Online (Sandbox Code Playgroud)