lundi 23 février 2015

Dynamic search function for UITableView in Swift

I'm trying to create a search function for my table view, but when I type in the second character in my text field, the function crashes. I can type in the first character, delete it, and type in a new one and it doesn't crash.


My error says:



fatal error: can not increment endIndex



and my code looks like this:



func textFieldDidChange(textField: UITextField){
self.loadSearchData(textField.text)
}

func loadSearchData(searchString:String){

var arrayOfSearches: [String] = []
let index = count(searchString)

for company in self.companies{
let searchIndex = advance(company.startIndex, index)
if searchString == company.substringToIndex(searchIndex){
arrayOfSearches.append(company)
}
}
self.companiesToDisplay = arrayOfSearches
self.companiesTV.reloadData()
}


where my companiesToDisplay is the array being displayed by my table view.


I know the fault is in my let searchIndex = advance(company.startIndex, index) line but I don't know why it would create an error.


Any suggestions on how to solve this would be appreciated.


Aucun commentaire:

Enregistrer un commentaire