0

I am matching an substring in my suggestion array to make a Autocomplete text field.

func searchAutocompleteEntriesWithSubstring(substring: String)
{
    autocompleteUrls.removeAll(keepCapacity: false)

    for curString in countries
    {
        let myString:NSString! = curString as NSString

        let substringRange :NSRange! = myString.rangeOfString(substring)

        if (substringRange.location  == 0)
        {
            autocompleteUrls.append(curString)
        }
    }

    autocompleteTableView.reloadData()

}

But if the country I am searching is India and I start searching from "ndia", its not getting the suggestions, it should get that as well.

prabodhprakash
  • 3,825
  • 24
  • 48
Saty
  • 2,563
  • 3
  • 37
  • 88
  • Possible duplicate of [How do I check if a string contains another string in Swift?](http://stackoverflow.com/questions/24034043/how-do-i-check-if-a-string-contains-another-string-in-swift) – Bista Sep 29 '16 at 06:47
  • 1
    Think about it: When is `if (substringRange.location == 0)` true? – Martin R Sep 29 '16 at 06:52
  • Do you people actually read question or just put answers? Please read my exact requirement again. I want to match exact character wise.... If I start searching "dia", the search result also should return INDIA – Saty Sep 29 '16 at 06:52
  • @MartinR... I already did....Thanks for your feedback – Saty Sep 29 '16 at 07:07

1 Answers1

3

Use predicate instead:

let countries = ["india", "japan", "Indonesia", "bangladesh", "Australia"];

let predicate = NSPredicate(format: "SELF contains[c] %@", "ndia")

let autocompleteUrls = countries.filter { predicate.evaluateWithObject($0) }

print(autocompleteUrls) // output: ["india"]
Bista
  • 7,869
  • 3
  • 27
  • 55