Marco Marco - 1 year ago 241
Swift Question

Swift - Filter array

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:

console log

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

Answer Source

You need to lowercase both the search text as well as the name property when searching for strings using .range(of:.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download