Swift 3 filter matrix of dictionaries by string values ​​of a key in a dictionary

I have a class like

class FoundItem : NSObject { var id : String! var itemName : String! var itemId : Int! var foundBy : String! var timeFound : String! init(id: String, itemName: String, itemId: Int, foundBy: String, timeFound: String) { self.id = id self.itemName = itemName self.itemId = itemId self.foundBy = foundBy self.timeFound = timeFound } 

and I refer to him at

 class MapViewVC: UIViewController, MKMapViewDelegate { var found = [FoundItem]() var filterItemName : String() } 

My FoundItem generated into an array of dictionaries from my FoundItem class from a firebase request. Then I get the line of this itemName , which is created from another view controller, which is a collection view in the didSelection function. I want to take this string and then filter or search for arrays with the string itemName , which is equal to the string itemName from my previous viewController . Then delete the array of dictionaries that are not equal to itemName . Not only objects, but the entire array containing a pair of unequal keys, values. I searched for a few days and am stuck in filtering an array of dictionaries created from a class. I looked and tried NSPredicates, for-in loop, but all that ends is creating a new array or bool that finds my values ​​or keys equal. Here is the current function I wrote.

 func filterArrayBySearch() { if self.filterItemName != nil { dump(found) let namePredicate = NSPredicate(format: "itemName like %@", "\(filterItemName)") let nameFilter = found.filter { namePredicate.evaluate(with: $0) } var crossRefNames = [String: [FoundItem]]() for nameItemArr in found { let listName = nameItem.itemName let key = listName if crossRefNames.index(forKey: key!) != nil { crossRefNames[key!]?.append(nameItemArr) if !("\(key)" == "\(filterItemName!)") { print("------------- Success have found [[[[[[ \(key!) ]]]]]] and \(filterItemName!) to be equal!!") // crossRefNames[key!]?.append(nameItemArr) } else { print("!! Could not find if \(key!) and \(filterItemName!) are equal !!") } } else { crossRefNames[key!] = [nameItemArr] } } } else { print("No Data from Search/FilterVC Controller") } } 

Can anyone help? It seems like it would be a simple task to find the value, and then filter out dictionaries that are not equal to the string itemName , but I continue to hit the wall. And I run into loops for myself: P is trying different things to achieve the same task.

+5
source share
4 answers

I hope I understand what you are asking. You mention the "array of dictionaries", but in fact you do not have a set of dictionaries anywhere in the code that you placed.

As far as I can tell, you are asking how to find all the entries in the found array for which itemName is equal to the filterItemName property.

If so, all you have to do is:

let foundItems = found.filter { $0.itemName == filterItemName }

What is it.


Some other ideas:

If you want to find elements in which filterItemName contained in itemName , you can do something like this:

let foundItems = found.filter { $0.itemName.contains(filterItemName) }

You can also use the lowercased() function if you want to do a case insensitive search.

You can also return the properties of the elements found in the array:

let foundIds = found.filter { $0.itemName == filterItemName }.map { $0.itemId }

+13
source

Sort dictionary array as follows

 var dict:[[String:AnyObject]] = sortedArray.filter{($0["parentId"] as! String) == "compareId"} 

The filter function moves through each element in the collection and returns a collection containing only elements that satisfy the include condition.

We can get one object from this dictionary array, you can use the following code

 var dict = sortedArray.filter{($0["parentId"] as! String) == "compareId"}.first 

OR

  let dict = sortedArray.filter{ ($0["parentId"] as! String) == "compareId" }.first 
+3
source

Here I use CoreData and I have an array of vocabulary. Here I filter the paymentToInvoice key, the value of which is an array of invoices, then the invoiceToPeople key, the key of which contains the user dictionary, then I search FirstName, lastName, several organization keys contain searchText. I hope this helps. Please try this. Thanks.

  var searchDict = dict.filter { (arg0) -> Bool in let (key, value) = arg0 for paymentInfo in (value as! [PaymentInfo]){ let organization = (Array((value as! [PaymentInfo])[0].paymentToInvoice!)[0] as! InvoiceInfo).invoiceToPeople?.organization let firstName = (Array((value as! [PaymentInfo])[0].paymentToInvoice!)[0] as! InvoiceInfo).invoiceToPeople?.firstName let lastName = (Array((value as! [PaymentInfo])[0].paymentToInvoice!)[0] as! InvoiceInfo).invoiceToPeople?.lastName return organization?.localizedStandardRange(of: searchText) != nil || firstName?.localizedStandardRange(of: searchText) != nil || lastName?.localizedStandardRange(of: searchText) != nil } return true } 
0
source

A local search filter that uses a predicate in an array of dictionary objects with a key name, this code is also used for both swift3 and swift4,4.1.

  func updateSearchResults(for searchController: UISearchController) { if (searchController.searchBar.text?.characters.count)! > 0 { guard let searchText = searchController.searchBar.text, searchText != "" else { return } usersDataFromResponse.removeAll() let searchPredicate = NSPredicate(format: "userName CONTAINS[C] %@", searchText) usersDataFromResponse = (filteredArray as NSArray).filtered(using: searchPredicate) print ("array = \(usersDataFromResponse)") self.listTableView.reloadData() } } 
-1
source

Source: https://habr.com/ru/post/1259659/


All Articles