Прежде всего вы должны обработать случай, если поле поиска пусто.
И есть более эффективный и надежный синтаксис для фильтрации массива: range(of
может фильтровать без учета регистра и с самого начала строки (anchored
) одновременно.
extension ViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
searching = false
wordSearch.removeAll()
} else {
wordSearch = wordArray.filter{ $0.range(of: searchText, options: [.caseInsensitive, .anchored]) != nil }
searching = true
}
tableView.reloadData()
}
}
Чтобы исправить ошибку, вы должны получить данные из wordSearch
или wordArray
в зависимости от searching
. Заменить numberOfRowsInSection
и cellForRowAt
на
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searching ? wordSearch.count : wordArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for indexPath)
let word = searching ? wordSearch[indexPath.row] : wordArray[indexPath.row]
cell.textLabel?.text = word
return cell
}