Filtering array of dictionaries in Swift

纵饮孤独 提交于 2019-11-30 16:02:21

Try This for 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()
}

I suggest using Swift's filter instead:

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()
}

And as mentioned by @LeoDabus in his comment, you can even simplify further:

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    let filteredArray = arrContact.filter { $0["Name"] == searchText }
    print(filteredArray)
    searchActive = !filteredArray.isEmpty
    tblData.reloadData()
}

where "name" is the key 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!