Search code examples
arraysswiftfiltercontains

Filter two values in array of objects


I have an array of objects and I want to filter them by two conditions, either if object is in an certain group or if it has an certain name but I can not figure out why it is not working.

This is my code:

let outputfiler = array.filter({$0.group.contains (where: {$0 == "groupBig" }) } || $1.name.contains(where: {$1 == "Eis"})  )

This is the error I get:

Anonymous closure argument not contained in a closure

Edit: Group is an array of trings, name just a string.

I also tried this:

outputfiler = array.filter{$0.group.contains (where: {$0 == "groupBig" }) || $0.name(where: {$0 == "Eis"}) }

But then I get this error:

Extraneous argument label 'where:' in call

Solution

  • You need your filter as follows (shown on multiple lines for clarity):

    let outputfiler = array.filter({
        $0.group.contains(where: { $0 == "groupBig" }) || 
        $0.name.contains("Eis")
    })
    

    You had the filter's closing } before the ||. And assuming name is a String, contains just takes the string to search, not a closure.