iOS Dev
iOS Dev

Reputation: 33

search a particular record in table view controller iOS swift

I am fetching data from url using jsonserialization method and stores each and every record in an object of a class and displays each record in table vc.

Now I want to implement search using search bar and watch many tutorials which had comparison between array of string type and another array of string type(Hardcoded values in array). But according to my need, my data is store in class obj not hardcoded data and data from that object is displayed on cellforrow. cellforrow contains.

if isSearching 
{
    cell.textLabel?.text = searchArray[indexPath.row] //.compName

    cell.detailTextLabel?.text = searchArray[indexPath.row]
}
else{ 
    cell.textLabel?.text = tempArray[indexPath.row].compName

    cell.detailTextLabel?.text = tempArray[indexPath.row].complocation
}
return cell

So how to implement search bar, getting following error. kindly help! here my classname is -> comp. and searchArray is array of strings and tempArray is array which contains class obj

Image of the error

Upvotes: 1

Views: 618

Answers (3)

Neeraj Joshi
Neeraj Joshi

Reputation: 769

Use this:

searchArray = searchArray.filter{(($0["name"]?.localizedCaseInsensitiveContains(textField.text!)))!}

Upvotes: 0

iOS Dev
iOS Dev

Reputation: 33

Found it. here's it is following is change in else condition

searchArr   = tempArray.filter { $0.<classAttribute>.contains(searchText) }

searchArray = searchArr as! [comp]

print("search match")

listTableView.reloadData()

here searchArr and searchArray and tempArray are array of class type, & classAttribute is ATTRIBUTE of that class that you want to search in tableview, my class name is "comp"

Upvotes: 1

Ladislav
Ladislav

Reputation: 7283

Then you just have to modify search filter you use to be:

searchArray = tempArray.filter({$0.compName == searchBarClicked.text!})

Compiler was telling you that you cannot compare $0 which is of type comp to searchBarClicked.text which is String, so $0.compName will be String and thus == can be used

Upvotes: 0

Related Questions