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