Hi, I have a view controller with a searchBar and 2 tableViews. I run a query to Firebase and the results are shown in the top tableView (chargesTableView). The bottom tableView has a listener that when I select a row from the top tableView the values are displayed at the bottom (this is working OK). The searchBar is to filter the results in the top tableView (chargesTableView), the problem I'm having is with the search logic, no matter what I do when I type 1, 2 or 3 letters of the item I'm looking for, I don't get the result I want, sometimes I get an item that contains the first letter or sometimes i don't get anything at all. I don't know what else to do/check/try to get this working as expected. I want to be able to type the first 2,3 letters and get the list of items in the array. Any help is greatly appreciated. Here is my code:
Code Block class ChargesVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate { var chargesClassFromCell = [Charges]() var filteredCharges = [Charges]() var searchBar = UISearchBar() var inSearchMode: Bool = false override func viewDidLoad() { super.viewDidLoad() searchBar.delegate = self } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { searchBar.showsCancelButton = true } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.endEditing(true) searchBar.showsCancelButton = false searchBar.text = nil inSearchMode = false } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { let searchText = searchBar.text!.lowercased() if searchText.isEmpty || searchText == " " { inSearchMode = false chargesTableView.reloadData() } else { inSearchMode = true filteredCharges = chargesClassFromCell.filter({ (searchResult) -> Bool in return searchResult.chargeDescription.contains(searchText) }) chargesTableView.reloadData() } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == chargesTableView { if inSearchMode { return filteredCharges.count } else { return chargesClassFromCell.count } } else { if tableView == patChargesTableView { } } return patChargesClassFromCell.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if tableView == chargesTableView { let cell = tableView.dequeueReusableCell(withIdentifier: "ChargesCell", for: indexPath) as? ChargesCell var charges: Charges! if inSearchMode { charges = filteredCharges[indexPath.row] } else { cell!.configureChargesListCell(charges: chargesClassFromCell[indexPath.row]) } cell!.charges = charges return cell! } else if tableView == patChargesTableView { let cell = tableView.dequeueReusableCell(withIdentifier: "PatChargesCell", for: indexPath) as? PatChargesCell cell!.configurePatChargesListCell(patCharges: patChargesClassFromCell[indexPath.row]) cell!.patChargesCount.text = "\(indexPath.row + 1)" + " - " return cell! } return UITableViewCell() }