Marco Marco - 1 year ago 247
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
} else {

inSearchMode = true

let lower = searchBar.text!.lowercased()

filteredNames = names.filter({$ lower) != nil})

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