Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter and sort swift array

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

like image 556
Ranjit Avatar asked Aug 02 '16 10:08

Ranjit


1 Answers

You can just write

 let result = words
    .filter { $0.contains(keyword) }
    .sorted { ($0.hasPrefix(keyword) ? 0 : 1) < ($1.hasPrefix(keyword) ? 0 : 1) }

Example

let words = ["apple", "workshops", "shopping", "sports", "parties", "pantry", "pen", "cat", "house"]
let keyword = "p"
let result = words
    .filter { $0.contains(keyword) }
    .sorted { ($0.hasPrefix(keyword) ? 0 : 1) < ($1.hasPrefix(keyword) ? 0 : 1) }

// ["pen", "pantry", "parties", "apple", "workshops", "shopping", "sports"]
like image 72
Luca Angeletti Avatar answered Oct 21 '22 08:10

Luca Angeletti