0

My data array is ["Apple", "Pear", "Banana", "Orange"].

If I search Apple, my filteredArray returns "Apple".

However, if I search "apple", it returns nothing.

I tried using the localizedCaseInsensitiveContains method posted as an answer in a similar question but it didn't seem to work for me. Any help is appreciated.

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        filteredArray = dataArray.filter({$0.prefix((textField.text?.count)!) == textField.text!})
        tableViewSearch.reloadData()
        return true
    }
Raf A
  • 23
  • 5
  • `{$0.prefix((textField.text?.count)!) == textField.text!}` I don't understand that. Isn't it `$0.hasPrefix(textField.text)`? And using `!` is usually a bad idea. – Larme Apr 09 '20 at 21:15
  • https://stackoverflow.com/a/42756282/1801544 – Larme Apr 09 '20 at 21:19
  • Ah yes, I got rid of .count in the end. Why is `!` a bad idea? – Raf A Apr 10 '20 at 11:54

2 Answers2

1

I tested this on a playground:

let searchText = "apple"
let dataArray = ["Apple", "Pear", "Banana", "Orange"]
let filteredArray = dataArray.filter{ $0.lowercased().hasPrefix(searchText.lowercased()) }
print(filteredArray)

You have to use hasPrefix to achieve what you want, and in order for the query to be case insensitive you can lowercase both your array and the query string.

NicolasElPapu
  • 1,612
  • 2
  • 11
  • 26
0

If you lowercase both the textField value and the values you are testing, the comparison will ignore capitalization:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    guard let testString = textfield.text?.lowercased() else { return true }

    filteredArray = dataArray.filter { $0.lowercased() == testString }
    return true
}

you could also filter for qualifying results-- things that contain what you are typing:

   filteredArray = dataArray.filter { $0.lowercased().contains(testString) }

or things that begin with what you are typing:

   filteredArray = dataArray.filter { $0.lowercased().starts(with: testString) }
HalR
  • 11,411
  • 5
  • 48
  • 80
  • The accepted solution was more in line with the question but I did end up using the .contains method so thank you very much for this! – Raf A Apr 10 '20 at 11:48