I have a swift array which I want to filter, here is the array
let array = [apple,workshops,shopping,sports,parties,pantry,pen]
I want to filter the array in such a way that the items beginning with the search string to appear before items that just contain the search string
So when i search for example p, then the results should be in some way
let array = [parties,pantry,pen,apple,workshops,shopping,sports]
I tried this
tagSearchResults = tagSearchResults.filter({ (interestTag:InterestTag) -> Bool in
let tmp: NSString = interestTag.tag
let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
return range.location != NSNotFound
})
but this gives me all strings containing the search string.
So guys how can i do this
Try this. Firstly, it filters the array to remove those elements that do not contain the search string, then uses a custom sort to prefer items that start with the search string. In general, use the Cartesian approach of splitting a problem into smaller sub-problems, rather than try to solve it all in one step.
Another way:
(I don't know why, but my Xcode took huge time to compile these lines. Believe this compiles and runs as expected eventually.)
You can just write
Example