我的代码有一个简单的问题。 我不会像在Facebook Messenger中那样进行搜索-我是什么意思? 我有多个字符串转换为一个字符串,没有空格
“我的字符串驼羊”->“ mystringllama”
我想让搜索者搜索两个或多个单词,例如: 当我键入“我的妈妈”时,我要搜索包含这些字符的每条记录。 有人可以帮忙吗?
我的代码:
func searchFor(text: String) {
if text == "" || text.count == 0 {
loadPricesFromDb()
}
else {
let realm = try! Realm()
self.items = []
let prices = realm.objects(Price.self)
let results = prices.filter({($0.MultipleSearchString?.lowercased().contains(text.rangeOfCharacter(from: text)))!
})
self.items.append(contentsOf: results)
self.tableView.reloadData()
}
}
我只是想把它做好。现在,我不知道要使用什么过滤器来进行良好的搜索。。::
答案 0 :(得分:0)
您可能会找到一个数据库命令来进行这种搜索。如果我理解您的要求正确,那么迅速构造如下这样的谓词就很容易。
let multipleSearchString = "my stg l la ma"
let texts = ["mystringlladm1a", "mystr2ingllama", "mystri2ngllama", "mys3ringllama"]
let key = multipleSearchString.compactMap{ $0 == " " ? nil : String($0) + "*"}.joined()
let predicate = NSPredicate(format: "SELF like[c] %@", argumentArray: [key])
print (texts.filter{predicate.evaluate(with: $0)})
//["mystringlladm1a", "mystr2ingllama", "mystri2ngllama"]
在您添加的情况下,可以添加计算属性以实现您的目标:
// extension Price{
// var lowerCasedMultipleSearchString: String{
// if let string = self.MultipleSearchString?.lowercased(){
// return string
// }
// return ""
// }
// }
// func searchTextInPrices(prices: Results<Price>, text: String) -> //Results<Price> {
// let key = text.compactMap{ $0 == " " ? nil : String($0) + "*"}.joined()
// let predicate = NSPredicate(format: "SELF like[c] %@", argumentArray: [key])
// return prices.filter{predicate.evaluate(with: $0.lowerCasedMultipleSearchString)}
// }
func searchFor(text: String) {
if text == "" || text.count == 0 {
loadPricesFromDb()
}
else {
let realm = try! Realm()
self.items = []
let prices = realm.objects(Price.self)
//The changed codes here.
let key = text.compactMap{ $0 == " " ? nil : String($0) + "*"}.joined()
let predicate = NSPredicate(format: "SELF like[c] %@", argumentArray: [key])
let results = prices.filter{predicate.evaluate(with: ($0.MultipleSearchString?.lowercased())!)}
//second edition:
var result = prices
var length : Int = 0
repeat{
let key = text[...(text.index(text.startIndex, offsetBy: length))].compactMap{ $0 == " " ? nil : String($0) + "*"}.joined()
let predicate = NSPredicate(format: "SELF like[c] %@", argumentArray: [key])
results = prices.filter{predicate.evaluate(with: ($0.MultipleSearchString?.lowercased())!)}
length += 1} while(length < text.count)
//Third edition:
let results = prices.filter{ text.reduce((($0.MultipleSearchString?.lowercased())!, true)){
if !$0.1 {return ("",false)}
else if let index = $0.0.index(of: $1) {return (String($0.0[index...]),true)}
return ("",false)
}.1}
self.items.append(contentsOf: results)
self.tableView.reloadData()
}
}