Skip to content

Instantly share code, notes, and snippets.

@coryalder
Created November 19, 2015 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coryalder/573116711a2e03539f8c to your computer and use it in GitHub Desktop.
Save coryalder/573116711a2e03539f8c to your computer and use it in GitHub Desktop.
Autocomplete filter code from Rivet's autocomplete suggestion engine
// depends on https://github.com/coryalder/LevenshteinSwift
class SuggestionController {
// has a couple of notable vars:
// delegate, where the inputted text is loaded from
// rawCompletions, an array of possible suggestions (unfiltered)
// autocompletions, the filtered array of suggestions we're offer up to the user
func filterAutocompletions() {
let campaignField = delegate!.campaignField
let _ = delegate?.longUrl
guard let string = campaignField.text where string.characters.count > 0 else {
self.autocompletions = self.rawCompletions
suggestionTable.reloadData()
return
}
var mapped = rawCompletions.map {
($0.limit(string.characters.count).asciiLevenshteinDistance(string), $0)
}
mapped.sortInPlace {
$0.0 < $1.0
}
let resultsCount = max(mapped.count - 1, 0)
let lim = min(resultsCount, 10)
// protect against 0...lim when lim == 0
let slice: Array<(Int, String)> = {
if lim > 0 {
return Array(mapped[0...lim])
} else {
return mapped
}
}()
let out = slice.map {
$0.1
}
self.autocompletions = out
suggestionTable.reloadData()
}
}
// limit strings to a specific length. "twitter".limit(2) == "tw"
public extension String {
func limit(n: Int) -> String {
let actual = min(self.characters.count, n)
let ind = startIndex.advancedBy(actual)
return substringToIndex(ind)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment