view raw
Saty Saty - 7 months ago 38
Swift Question

Searching for a substring in string in Swift not working

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)



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.


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