我有一个带字典的数组示例:
(
{
Email = "kate-bell@mac.com";
Name = "Kate Bell";
Number = "(555) 564-8583";
},
{
Email = "d-higgins@mac.com";
Name = "Daniel Higgins";
Number = "555-478-7672";
}
)
我想根据Key" Name"过滤这个词典。
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let predicate = NSPredicate(format:"Name == %@", searchText)
let filteredArray = (arrContact as NSMutableArray).filteredArrayUsingPredicate(predicate)
print(filteredArray)
if(filteredArray.count == 0){
searchActive = false;
} else {
searchActive = true;
}
tblData.reloadData()
}
我总是从上面的swift代码得到空数组。请帮我解决这个问题。感谢
答案 0 :(得分:8)
尝试使用swift 3
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
// Put your key in predicate that is "Name"
let searchPredicate = NSPredicate(format: "Name CONTAINS[C] %@", searchText)
let array = (arrContact as NSArray).filtered(using: searchPredicate)
print ("array = \(array)")
if(array.count == 0){
searchActive = false;
} else {
searchActive = true;
}
self.aTable.reloadData()
}
答案 1 :(得分:6)
我建议使用Swift的filter
代替:
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let filteredArray = arrContact.filter { $0["Name"] == searchText }
print(filteredArray)
if filteredArray.isEmpty {
searchActive = false
} else {
searchActive = true
}
tblData.reloadData()
}
正如@LeoDabus在评论中所提到的,你甚至可以进一步简化:
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let filteredArray = arrContact.filter { $0["Name"] == searchText }
print(filteredArray)
searchActive = !filteredArray.isEmpty
tblData.reloadData()
}
答案 2 :(得分:0)
其中"姓名"是关键名称
var namePredicate = NSPredicate(format: "Name like %@", String(searchText));
let searchPredicate = NSPredicate(format: "Name CONTAINS[C] %@", searchText)
arrrDict = self.arrrDict.filter { searchPredicate.evaluate(with: $0) };
you will get the result in dictionary specialy made to get contats from the phone book