SWIFT2 – Filtering character in SWIFT

I have an example of an array with a dictionary:

(
{
Email = " [email protected]";
Name = "Kate Bell";
Number = "(555) 564-8583";
},
{
Email = "[email protected]";
Name = "Daniel Higgins";
Number = "555-478-7672";
}
)

I want to filter this dictionary based on the 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 always get empty array from above swift code. Please help me to solve this problem. Thank you

Try this 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 have one Example of array with dictionary:

(
{
Email = "[email protected]";
Name = "Kate Bell";
Number = "(555) 564-8583";
},
{
Email = "[email protected]";
Name = "Daniel Higgins";
Number = "555-478-7672";
}
)

I want to filter this based on the key “name” Dictionary

func searchBar(searchBar: UISearchBar, textDidCha nge 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 always get an empty array from the swift code above. Please help me to solve this problem. Thank you

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

Leave a Comment

Your email address will not be published.