SoundShock SoundShock - 4 months ago 10
iOS Question

How to add two Range<Index> together?

so I am filtering data (all strings), and want to show the following:


  1. The search words where the first letters contain your search (example. when searching 'Br' I want to see all the words that begin with 'Br' like Break, Broke,...)

  2. The search words where the string contains the word (example. When searching 'Br' is shows all words containing 'br' in the word like 'groundbreaker').



I've got both of them to work separately (see
let found
and
let foundMore
), but now I want to merge both of them (first showing the search words where the first letter contains your search, after the ones where the string contains the word). Tried using the addition sign, but it gives the following error


Binary operator '+' cannot be applied to two 'Range?' operands


extension SearchResultsController : UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
self.tableView.reloadData()
let searchBar = searchController.searchBar
let target = searchBar.text!
self.filteredData = self.originalData.filter {
s in
let options = NSStringCompareOptions.AnchoredSearch
let found = s.rangeOfString(target, options: options)

let optionsMore = NSStringCompareOptions.CaseInsensitiveSearch
let foundMore = s.rangeOfString(target, options: optionsMore)

let allTogether = found + foundMore

return (allTogether != nil)
}
self.tableView.reloadData()
}
}

Answer

Ranges cannot be added together, because the result may not be a proper range when the two ranges do not intersect.

However, you do not need to add this, because in the end you compare the overall range to nil. This means that you can compare the two sides to nil individually:

return s.rangeOfString(target, options: NSStringCompareOptions.AnchoredSearch) != nil
    || s.rangeOfString(target, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil

check 1. and 2., should be viewed like this, not a mix of both

Then you should filter twice, and append the second array to first one:

var filtered1 = self.originalData.filter { s in
    return s.rangeOfString(target, options: NSStringCompareOptions.AnchoredSearch) != nil
}
let filtered2 = self.originalData.filter { s in
    // Exclude results of the first search
    return s.rangeOfString(target, options: NSStringCompareOptions.AnchoredSearch) == nil
 && s.rangeOfString(target, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil
}
filtered1 += filtered2
self.filteredData = filtered1