[Solved] Multiple search in string – swift 4+


You may find a database command to get this kind of search. In swift, it’s easy to construct such a predicate like the following if I understand your requirement right.

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

In your added case, a computed property can be added to achieve your goal:

  //  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()
}
}

1

solved Multiple search in string – swift 4+