Search within dictionary in Swift - ios

I'm getting NSDictionary from JSON response
How can search within an NSDictionary of Arrays.Each array contains a NSDictionary. I want to search for particular casino name but i also want to get the address field with associated with it . How can i get it in swift ios.
The JSON response is below
{
"success": [
{
"casino_id": "2",
"casino_name": "cas",
"address": "add",
"distance": "0.19084827576745822"
},
{
"casino_id": "4",
"casino_name": "eeee",
"address": "adressdd",
"distance": "0.12319974564234398"
}
]
}
code for searching iss below
var casinoarray = NSArray() // CONTAINS THE JSON
var resultsarray = NSArray() // USED FOR FILTERED ARRAY
let resultPredicate = NSPredicate(format: "self.casino_name == %#", searchText)
resultsarray = casinoarray.filteredArrayUsingPredicate(resultPredicate)
tableView.reloadData()
print(resultsarray)
Please help me with it.
TIA

You can use like this
let prdicate:NSPredicate = NSPredicate(format: "self.casino_name contains[c] %#", searchText)
let filterArray = self.yourArray.filter({
prdicate.evaluateWithObject($0)
})
print(filterArray)

Related

Array of dictionary filter using predicate - swift3

I have array of dictionaries.
>[{"name": "John",
"address":
{"home": "addr1",
"work": "add2"}
},
{"name": "Anu",
"address": {"home": "addr1",
"work": "add2"}
}]
I am saving it to user default like this -
let personsData1 = ["name": "John", "address": {"home": "addr1", "work": "add2"}] as [String : Any]
let personsData2 = ["name": "Anu", "address": {"home": "addr1", "work": "add2"}] as [String : Any]
var persons = [personsData, personsData1]
UserDefaults.standard.set(forKey: "persons")
Retrieving it in another method and filter them on the basis of name.
let name = "John"
Getting below error
Cannot invoke 'filter' with an argument list of type '((Any?) -> Bool)'
Here is the code :-
func test () {
let personData1 = ["name": "John", "addresses": ["home":"addr1", "work": "addr2"]] as [String : Any]
let personData2 = ["name": "And", "addresses": ["home":"addr1", "work": "addr2"]] as [String : Any]
let persons = [personData1, personData2]
(UserDefaults.standard.set(persons, forKey: "persons")
print("Saved ----\(UserDefaults.standard.value(forKey: "persons"))")
if let savedPersons = UserDefaults.standard.value(forKey: "persons") {
let namePredicate = NSPredicate(format: "name like %#", name);
var filteredArray: [[String:Any]] = savedPersons.filter { namePredicate.evaluate(with: $0) }
print("names = \(filteredArray)")
}
}
If I try to filter like this -
let filteredArray = savedBrs.filter { $0["name"] == name }
getting different error -
Value of type 'Any' has no member 'filter'
With NSPredicate
let arr = [["name":"Rego","address":["one":"peek","two":"geelo"]],["name":"pppp","address":["one":"peek","two":"geelo"]]]
let neededName = "Rego"
let pre = NSPredicate(format: "name == %#",neededName)
let result = arr.filter { pre.evaluate(with:$0) }
print(result)
Without NSPredicate
let result = arr.filter { $0["name"] as? String == neededName }

How to filter an array using NSPredicate in swift 3

I have an arraycontaining several dictionaries.
{
DisplayName?:"Name of the employee"
Age:28
Department:"Dept 2"
}
I just converted my objective-c code into swift and trying to filter like this.
let exists = NSPredicate(format: "DisplayName2 CONTAINS[cd] \(searchText!)")
let aList: Array<Any> = arrayDirectory.filter { exists.evaluate(with: $0) }
if(aList.count>0)
{
arrayDirectory=aList
facesCarousel.reloadData()
}
But I am always getting the aList count as 0. It seems like not filtering my array. How can I write proper NSPredicatein swift 3 and filter my array using it.
To make this filter in Swift doesn't require NSPredicate at all.
let array = arrayDirectory.filter {
guard let name = $0["DisplayName"] as? String else {
return false
}
return name.contains(searchText)
}
That should be all you need.
EDIT
Updated to match your dictionary. I think this is what you're doing.
Ideally, you shouldn't be using a standard Dictionary as a working object. Convert your array of dictionaries to an array of Structs. That way you don't need to stringly type your code or unwrap properties that aren't really optional.
Workaround for working with an [Any] array...
Because you have defined your array as [Any] (don't do this) you will need to convert the object to a dictionary first.
let array = arrayDirectory.filter {
guard let dictionary = $0 as? [String: Any],
let name = dictionary["DisplayName"] as? String else {
return false
}
return name.contains(searchText)
}
The native Swift equivalent to the ObjC code is
let filteredArray = arrayDirectory.filter { ($0["displayName2"] as! String).range(of: searchText!, options: [.diacriticInsensitive, .caseInsensitive]) != nil }
assuming arrayDirectory is a native Swift Array. It considers also the case insensitive and diacritic insensitive parameters.
you can try
self.arrayDirectory.filter({(($0["Age"] as! String).localizedCaseInsensitiveContains(searchText))!})
Use this code my code will help you
let predicate = NSPredicate(format: "DisplayName2 contains[c] %#", textField.text!)
let arr : NSArray = arrayDirectory.filtered(using: predicate) as NSArray
if arr.count > 0
{
arrayDirectory=arr
facesCarousel.reloadData()
}
Use this code its worked fine in my side I hope this code will be help you
I have an array that array containing several dictionaries. Structure will be like this
[
{
DisplayName:"Name of the employee1"
Age:28
Department:"Dept 2"
}
]
In above array i am filtering with displayName key using apple search controller with help of predicate method
func updateSearchResults(for searchController: UISearchController) {
if (searchController.searchBar.text?.characters.count)! > 0 {
guard let searchText = searchController.searchBar.text, searchText != "" else {
return
}
let searchPredicate = NSPredicate(format: "DisplayName CONTAINS[C] %#", searchText)
usersDataFromResponse = (filteredArray as NSArray).filtered(using: searchPredicate)
print ("array = \(usersDataFromResponse)")
self.tableview.reloadData()
}
}

Search in Array of Dictionaries by key name

I have an array of dictionary, in which i need to search and return matching Dict
let foo = [
["selectedSegment":0, "severity":3, "dataDictKey": "critical"],
["selectedSegment":1, "severity":2, "dataDictKey": "major"],
["selectedSegment":2, "severity":1, "dataDictKey": "minor"],
]
In foo, how can i find for severity:2 and get matching Dict ?
Use the filter function
let foo = [
["selectedSegment":0, "severity":3, "dataDictKey": "critical"],
["selectedSegment":1, "severity":2, "dataDictKey": "major"],
["selectedSegment":2, "severity":1, "dataDictKey": "minor"],
]
let filteredArray = foo.filter{$0["severity"]! == 2}
print(filteredArray.first ?? "Item not found")
or indexOf
if let filteredArrayIndex = foo.indexOf({$0["severity"]! == 2}) {
print(foo[filteredArrayIndex])
} else {
print("Item not found")
}
or NSPredicate
let predicate = NSPredicate(format: "severity == 2")
let filteredArray = (foo as NSArray).filteredArrayUsingPredicate(predicate)
print(filteredArray.first ?? "Item not found")
Swift 3 Update:
indexOf( has been renamed to index(where:
filteredArrayUsingPredicate(predicate) has been renamed to filtered(using: predicate)
if let index = foo.flatMap({ $0["severity"] }).indexOf(2) {
print(foo[index])
}
Another way of doing it.
The first example only works if the user is 100% sure all the dictionaries contains "severity" as a key. To make it more safe:
if let index = foo.indexOf({ ($0["severity"] ?? 0) == 2 }) {
print(foo[index])
}
if you work on swift 3.1 -
let resultPredicate : NSPredicate = NSPredicate.init(format: "<your Key> CONTAINS [cd] %#", <value which you want to search>)
let filteredArray = requstData.arrayForColl?.filter { resultPredicate.evaluate(with: $0) };

Filter AnyObject in Swift 2

I have an JsonArray named data which I pass to AnyObject:
if let dtMenu: AnyObject = responseObject?.valueForKey("data") {
print(filteredMenu)
}
// I got JsonArray here
// My data are
"data":[
{
"MENUITEMID":1.0,
"MENUITEMNAMEENG":"IGW",
"MENUITEMHREF":"IGW_1",
"MENUITEMTYPE":"R",
"MENUITEMLEVEL":1.0,
"MENUGRPID":0.0,
"MENUGRPSERIAL":1.0
},
{
"MENUITEMID":6.0,
"MENUITEMNAMEENG":"Dashboard",
"MENUITEMHREF":"Dashboard_IGW",
"MENUITEMTYPE":"L",
"MENUITEMLEVEL":2.0,
"MENUGRPID":1.0,
"MENUGRPSERIAL":1.0
}]
//I want to filter array by MENUITEMTYPE=R
Please help..
Try this.
var predicate = NSPredicate(format: "%K == %#", "MENUITEMTYPE", "R")
let filteredArray = yourArray.filter { predicate.evaluateWithObject($0) };
I have not tested this yet.

swift NSDictionary filter using string

What I need is how we need to filter NSDictionary and return only the values and the keys where the key contain a string
For example if we have NSDictionary that contain :
{
"houssam" : 3,
"houss" : 2,
"other" : 5
}
and the string is "houss"
so we need to return
{
"houssam" : 3,
"houss" : 2
}
Best Regards,
You can use the filter function to get what you need like in the following way:
var dict: NSDictionary = ["houssam": 3, "houss": 2, "other": 5 ]
let string = "houss"
var result = dict.filter { $0.0.containsString(string)}
print(result) //[("houssam", 3), ("houss", 2)]
The above code return a list of tuples, if you want to get a [String: Int] dictionary again you can use the following code:
var newData = [String: Int]()
for x in result {
newData[x.0 as! String] = x.1 as? Int
}
print(newData) //["houssam": 3, "houss": 2]
I hope this help you.
Use this code to get matching keys.
var predicate = NSPredicate(format: "SELF like %#", "houss");
let matchingKeys = dictionary.keys.filter { predicate.evaluateWithObject($0) };
Then just fetch entries which keys are in matchingKeys array.
Since this is an NSDictionary, you can use the filteredArrayUsingPredicate: method on the array of keys, and fetch back the values from the initial dictionary.
For instance:
let data: NSDictionary = // Your NSDictionary
let keys: NSArray = data.allKeys
let filteredKeys: [String] = keys.filteredArrayUsingPredicate(NSPredicate(format: "SELF CONTAINS[cd] %#", "houss")) as! [String]
let filteredDictionary = data.dictionaryWithValuesForKeys(filteredKeys)
Hope that helps.

Resources