DevC DevC - 7 months ago 17
Swift Question

Efficient way to filter array of Person objects based on an array of string names

I have an array of names:

var namesArray = ["Bert","Tony","Phil","George", "David"]


I then have an array of Person Objects:

var personsArray: [Person]


And a snippet of my Person class is:

class Person {
var name: String

...some code omitted...
}


I am looking for a way to filter my array of Persons objects to only include the
Person
whos name is found in the
namesArray
.

I considered using the
.filter
on the array but I need to loop over two arrays.

let filterByNameArray = persons.filter({
($0.name == //string)!
})


But I believe this is incorrect as I need to loop through the names array also. I solved my issue using a double for loop:

var pArray: [Person] = []

for person in personsArray {

for nameString in namesArray {
if person.name == nameString {
pArray.append(person)
}
}
}


However, this is ugly and uses a significant amount of CPU so my question is,is there a more efficient way to do this? :) Im sure there is.

Answer

Use the contains method on the namesArray to search all of it.

let filteredByNameArray = persons.filter {
  namesArray.contains($0.name)
}