1

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.

4
  • Out of curiosity, why do you subclass NSObject? Commented May 5, 2016 at 15:30
  • @TimVermeulen no problem, I subclass NSObject so I can compare one Person object to another. Commented May 5, 2016 at 15:33
  • 1
    Don't do that. Implement the Equatable protocol instead. Commented May 5, 2016 at 15:35
  • @TimVermeulen thanks for the tip. Im just beginning Swift at the moment so I have plenty to learn. :) Commented May 5, 2016 at 15:36

1 Answer 1

1

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

let filteredByNameArray = persons.filter {
  namesArray.contains($0.name)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.