PCD PCD - 11 months ago 66
Swift Question

Filter an array of objects by an array of dictionaries contained in the object

So I need to filter an array of objects by an array contained in the object

the object looks like this

class thing {

let list = [stuff, stuff, stuff, stuff]


class stuff {

var name = "ugly"


The array looks like this

thingArray = [thing, thing, thing, thing]

and my code so far looks like this

newArray = thingArray.filter { receipt in

return thing.thingArray.lowercaseString.containsString(searchText.lowercaseString)

So my problem is that I can't get this function to work and what I really need is a way to filter this array of objects by the array contained inside of the object. Any help is definitely appreciated.

p.s. I just tried this to no avail:

test = thingArray.filter {$0.list.filter {$0.name.lowercaseString.containsString(searchText.lowercaseString) == true}}

Answer Source

If I understood correctly, your problem can be solved with something like this:

class thing {

init(list: [String]) {
    self.list = list

var list: [String]


let thingArray = [thing(list: ["one", "two", "three"]), thing(list: ["uno", "due", "tre"]), thing(list: ["uno", "dos", "tres"])]

let searchString = "uno"

let result = thingArray.filter {

//it will print "uno", "due", "tre"