Filtering array of dictionaries in Swift

2019-02-11 01:27发布

问题:

I have An Array With Dictionaries example :

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

And i want to filter this dictionary according to 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()
 }

I am always getting empty array in result from above swift code. Please help me to resolve this issue. Thanks

回答1:

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


回答2:

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


回答3:

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