[英]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 所以当我搜索例如p时,结果应该以某种方式
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 伙计们我该怎么做
You can just write 你可以写
let result = words
.filter { $0.contains(keyword) }
.sorted { ($0.hasPrefix(keyword) ? 0 : 1) < ($1.hasPrefix(keyword) ? 0 : 1) }
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"]
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.
通常,使用笛卡尔方法将问题分解为较小的子问题,而不是尝试一步一步解决所有问题。
let searchString = "p"
let array = ["apple", "workshops", "shopping", "sports", "parties", "pantry", "pen", "xyzzy"]
let filteredArray = array.filter({ $0.contains(searchString) })
filteredArray // drops xyzzy
let sortedArray = filteredArray.sorted(isOrderedBefore: {
switch ($0.hasPrefix(searchString), $1.hasPrefix(searchString)) {
case (true, true):
return $0 < $1
case (true, false):
return true
case (false, true):
return false
case (false, false):
return $0 < $1
}
})
sortedArray // "pantry", "parties", "pen", "apple", "shopping", "sports", "workshops"] as required
Another way: 其它的办法:
let searchString = "p"
let array = ["apple", "workshops", "shopping", "sports", "parties", "pantry", "pen", "xyzzy"]
let result = array.filter{$0.containsString(searchString)}
.map{($0.hasPrefix(searchString) ? 0 : 1, $0)}
.sort{$0 < $1}
.map{$1}
print(result) //->["pantry", "parties", "pen", "apple", "shopping", "sports", "workshops"]
(I don't know why, but my Xcode took huge time to compile these lines. Believe this compiles and runs as expected eventually.) (我不知道为什么,但是我的Xcode花了很多时间来编译这些行。相信这个编译并最终会按预期运行。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.