I have an array of characters and when I search and enter "Co" for example, I get two matches (I don’t want that). I want only what begins with a specific character to be searched.
I share the array of strings and the method textDidChange in swift
any suggestion please
`EX: listEmployed = ["Conejo","Tetera","Aviteon","Sacoja"]
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
isSearching = true
arrayFilterEmployed = listEmployed
if searchText.isEmpty == false {
arrayFilterEmployed = listEmployed?.filter({$0.text.lowercased().range(of: searchText.lowercased(), options: .caseInsensitive) != nil})
}
if arrayFilterEmployed?.count == 0 {
searchBar.showsCancelButton = false
fountLabel?.isHidden = false
}
else {
categoryTableView?.reloadData()
fountLabel?.isHidden = true
}
categoryTableView?.reloadData()
}`
I have an array of characters and when I search and enter "Co" for example, I get two matches (I don’t want that). I want only what begins with a specific character to be searched.
2
Answers
In your case, you can filter data by using the hasPrefix. It will filter out the data based on the text you entered in the search bar.
Replace the following line:
with (case-sensitive search)
and replace with the following (case-insensitive search)
You just need to add the
.anchored
option. And since you are using.caseInsensitive
, you don’t need the calls tolowercased()
:.anchored
means the check will only pass if at the start of the string. If the options also included.backwards
, then.anchored
would mean the match must be at the end of the string.