skip to Main Content

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


  1. 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:

    arrayFilterEmployed = listEmployed?.filter({$0.text.lowercased().range(of: searchText.lowercased(), options: .caseInsensitive) != nil})
    

    with (case-sensitive search)

    arrayFilterEmployed = listEmployed?.filter({$0.text.hasPrefix(searchText) != nil})
    

    and replace with the following (case-insensitive search)

    arrayFilterEmployed = listEmployed?.filter({$0.text.lowercased().hasPrefix(searchText.lowercased()) != nil})
    
    Login or Signup to reply.
  2. You just need to add the .anchored option. And since you are using .caseInsensitive, you don’t need the calls to lowercased():

    if !searchText.isEmpty {
        arrayFilterEmployed = listEmployed?.filter({$0.text.range(of: searchText, options: [.caseInsensitive, .anchored]) != nil})
    }
    

    .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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search