swift2 Swift中的字典过滤数组

8ljdwjyq  于 2022-11-06  发布在  Swift
关注(0)|答案(4)|浏览(272)

我有一个数组与字典的例子:

(
        {
        Email = "kate-bell@mac.com";
        Name = "Kate Bell";
        Number = "(555) 564-8583";
    },
        {
        Email = "d-higgins@mac.com";
        Name = "Daniel Higgins";
        Number = "555-478-7672";
    }
)

我想根据关键字“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代码的结果中得到空数组。请帮助我解决这个问题。谢谢

wkyowqbh

wkyowqbh1#

我建议使用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()
}
rkkpypqq

rkkpypqq2#

在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()
}
2izufjch

2izufjch3#

迅捷

从模型类中获取项/数组的列表。

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if self.searchBarItems.text == "" {
        self.arrFilter = self.arrayDictionarySubModel
    } else {
        self.arrFilter.removeAll()
        let filteredArray = self.arrayDictionarySubModel.filter { ($0.itemTitle?.contains(self.searchBarItems.text ?? ""))!}
        print("filtered array:- ", filteredArray[0].itemTitle!)
        self.arrFilter = filteredArray
    }
    self.searchItemTableView.reloadData()
}
ktca8awb

ktca8awb4#

其中“name”是密钥名称

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

相关问题