1

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

1
  • 1
    You need to do lowercased of your name when you do the range comparison. Commented Jul 26, 2017 at 14:40

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

can't believe it! in the last 2 days have lost my mind on stupid errors... that's not the first! :) thx a lot you've fixed it in 2 mins! :)
No worries @Marco! Feel free to accept if this fixed your problem.
1

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)

Comments

1

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.

2 Comments

thx! can't believe that in the last 2 days have lost my mind on stupid errors like this! :)
No worries, glad I could help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.