过滤和排序swift数组 [英] Filter and sort swift array

查看:86
本文介绍了过滤和排序swift数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我要过滤的swift数组,这里是数组

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

所以当我搜索示例p时,结果应该以某种方式

So when i search for example p, then the results should be in some way

let array = [parties,pantry,pen,apple,workshops,shopping,sports] 

我试过这个

tagSearchResults = tagSearchResults.filter({ (interestTag:InterestTag) -> Bool in
            let tmp: NSString = interestTag.tag
            let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
            return range.location != NSNotFound
        })

但这给出了我所有的字符串c提供搜索字符串。

but this gives me all strings containing the search string.

那么伙计我怎么能这样做

So guys how can i do this

推荐答案

你可以写

 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"]

这篇关于过滤和排序swift数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆