Search code examples
arraysswiftstructpredicate

Search in Array of dictionary with multiple keys


I have array of profile class:

let foo = [
    [profileClass],
    [profileClass],
    [profileClass],
]

Profile class is below :

class profileClass: modelclass {
  let name: String
  let severity: String
  let address : String

 init(name: String, severity: String, address: String){
    self.name = name
    self.severity = severity
    self.address = address
  }
}

How can i use predicate to perform search option in keys for name and address both.I am using below logic but it only filter from key "name" and it is not predicate. I wanted to use predicate and search result if string exist in "name" or in "address"

guard foo != nil, foo?.count ?? 0 > 0 && searchString != nil  else { return }
    var filteredfoo = foo?[0].modelclass.filter { viewModel -> Bool in
      return viewModel.name.containsIgnoringCase(find: searchString!)
    }

Solution

  • Just add || viewModel.address.containsIgnoringCase(find: searchString!) in return statement.

    So final return would look like this:

    return viewModel.name.containsIgnoringCase(find: searchString!) || viewModel.address.containsIgnoringCase(find: searchString!)