DevC DevC - 5 months ago 8
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
whos name is found in the

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

let filterByNameArray = persons.filter({
($ == //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 == nameString {

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.


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

let filteredByNameArray = persons.filter {