Saty Saty - 2 months ago 7
iOS Question

Matching the substring from the middle of the string

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.

Answer

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"]