Reputation: 1061
I'm having a bit of trouble with filtering an array.
I have this code:
var names = [Name]()
var filteredNames = [Name]()
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == ""{
inSearchMode = false
collectionView.reloadData()
view.endEditing(true)
} else {
inSearchMode = true
let lower = searchBar.text!.lowercased()
print(lower)
filteredNames = names.filter({$0.name.range(of: lower) != nil})
collectionView.reloadData()
}
}
The problem is that it seems not to see letters correctly. I've printed on the console the name Array, the filetredNames array and the searchBar.text here's the result:
how is possible that the "Discus" value is not included when typing the d? it happens with all letters (eg. discus return zero result and so on)
Thank you
Upvotes: 1
Views: 1249
Reputation: 54706
The problem is that you are only searching for the lowercased version of the searchbar input.
You should use localizedCaseInsensitiveContains
as the filter
criteria.
names.filter{$0.localizedCaseInsensitiveContains(searchBar.text!)}
This way you don't have to handle upper/lowercase separately by hand, both will be handled by the function automatically.
Upvotes: 1
Reputation: 12053
You need to lowercase both the search text as well as the name
property when searching for strings using .range(of:
.
Upvotes: 1
Reputation: 1292
The Problem
You have changed the searchText to be lowercase however your datasource (names) contains uppercase letters.
The Fix
Change:
$0.name.range(of: lower)
To:
$0.name.lowercased().range(of: lower)
Upvotes: 1