J.Doe
J.Doe

Reputation: 397

Filtering arrays with partial exact match?

I'm basically looking to exactly match how almost any search handles filtering.

Every guide for search filtering I've seen so far offers

let lower = searchBar.text!.lowercaseString

filteredInterestArray = interestsArray.filter({$0.title.rangeOfString(lower) != nil})

which basically gives something like:

["Cat", "Rat", "Bat", "Atlas"]

If you type in "at" every single one will show up, when really only Altas should show up. Also, if you typed in "stla", atlas would show up which is obviously very unintuitive.

How is proper filtering accomplished?

Upvotes: 1

Views: 431

Answers (2)

danh
danh

Reputation: 62686

NSString provides hasPrefix: to determine if a string starts with another.

The OP doesn't indicate whether the strings in interestsArray are lowercase to begin with, but if they aren't, you'll have to force them to lower before checking.

Upvotes: 1

Midhun MP
Midhun MP

Reputation: 107121

For achieving this, you can use the hasPrefix(_:) method instead of rangeOfString method.

Use:

let lower = searchBar.text!.lowercaseString
filteredInterestArray = interestsArray.filter({$0.title.hasPrefix(lower)})

Upvotes: 2

Related Questions