我有一个我要过滤的swift数组,这里是数组
Gemfile
我希望过滤数组,使得以搜索字符串开头的项目显示在仅包含搜索字符串的项目之前
所以当我搜索示例p时,结果应该是某种方式
let array = [apple,workshops,shopping,sports,parties,pantry,pen]
我试过这个
let array = [parties,pantry,pen,apple,workshops,shopping,sports]
但是这给了我包含搜索字符串的所有字符串。
那么伙计我怎么能这样做
答案 0 :(得分:17)
你可以写
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"]
答案 1 :(得分:13)
试试这个。首先,它过滤数组以删除那些不包含搜索字符串的元素,然后使用自定义排序来优先选择以搜索字符串开头的项目。一般来说,使用笛卡尔方法将问题分解为较小的子问题,而不是试图一步解决问题。
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
答案 2 :(得分:3)
另一种方式:
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"]
(我不知道为什么,但我的Xcode花了很多时间来编译这些行。相信这个编译并最终按预期运行。)