Im new to the swift, I am trying to filter name from an array using the search bar in console am getting what I entered in the search bar but filtering with predicate im not getting filtered name...please can anyone help in this issue
var caseListOfBooker:[CaseDetails]=[]
var searchString:String=""
var filteredString = [String]()
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
print("searchText \(searchText)")
searchString = searchText
updateSearchResults()
tableview.reloadData()
}
func updateSearchResults(){
filteredString.removeAll(keepingCapacity: false)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchString)
let array = self.caseListOfBooker.filter{$0.person_of_interest.contains(searchString)}
print(array)
if let list=array as? [String]{
filteredString=list
}
print(filteredString)
tableview.reloadData()
}
extension SearchPOIVC : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if filteredString != []{
return filteredString.count
}
else
{
if searchString != "[]" {
return caseListOfBooker.count
}else {
return 0
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80.00
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:POIProfileDetailsCell = tableview.dequeueReusableCell(withIdentifier: "POIProfileDetailsCell", for: indexPath) as! POIProfileDetailsCell
if filteredString != []{
cell.poiName.text = filteredString[indexPath.row]
return cell
}else{
if searchString != "[]"{
cell.poiName.text = self.caseListOfBooker[indexPath.row].person_of_interest
}
return cell
}
}
You are getting array of
CaseDetails
objects and trying to cast to array ofString
It fails. You need to get string values from the
CaseDetails
object and join themUse
Or
Instead of
The most efficient way to filter custom classes is to use the same type for the data source array and the filtered array
Add a property
isFiltering
which is set to true when the search text is not emptyand delete
searchString
andfilteredString
In
updateSearchResults
filter the data source array (with native Swift functions), setisFiltering
accordingly and reload the table viewIn the table view data source methods display the data depending on
isFiltering