Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Array with UISearchBar

I am currently using the following code to filter the array and present the results in my tableView. The problem is that this only returns results if the search matches the exact word. How do I change my array filter to search each character as I type it?

let data = ["Mango", "Grape", "Berry", "Orange", "Apple"]

var filteredData: [String] = []

filteredData = data.filter({$0 == searchBar.text})

The only way to get "Mango" to show up in my tableView, I have to type Mango in the search bar, typing "Man" doesn't show any results.

like image 386
Martheli Avatar asked May 31 '26 20:05

Martheli


2 Answers

Swift 5 Solution:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    filteredData = data

    if searchText.isEmpty == false {
        filteredData = data.filter({ $0.contains(searchText) })
    }

    tableView.reloadData()
}

This ensures that when the searchBar is empty, it goes back to displaying all your array's data, while also reloading the tableView every time you change the text.

like image 157
Michael Avatar answered Jun 03 '26 11:06

Michael


Try this:

filteredData  = data.filter { $0.contains(_ other: searchBar.text) }
like image 37
Joe Avatar answered Jun 03 '26 11:06

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!