3

I am trying compare two arrays. One array is an array of Person objects, each of which has an email property that is a String email address. The other array is an EmailAddress object which has a descriptive word like "work" or "personal" and the actual String email address.

Basically both objects have a String property for email address. I want to compare these arrays of objects to see if one of the objects from each array has the same email address. Right now I am using nested for loops as shown below but that is taking too long.

for person in self.allPeople! {
    for e in EmailAddresses! {
        if e.value == person.email {
             return true               
        }
    }
}

I thought about using set intersection but that looked like it would only work for comparing the same objects and not object's properties. Thanks.

Community
  • 1
  • 1
user3179636
  • 549
  • 3
  • 14

1 Answers1

3

You can still use Set functionality by first creating a set of all the emails. map helps turn one collection into another, in this case changing your collection of allPeople into a collection of those people's emails. This will be faster because now EmailAddresses is iterated once, instead of once per person.

let personEmails = Set(self.allPeople!.map { $0.email })
let matchingEmails = EmailAddresses!.map { $0.value }
return !personEmails.isDisjoint(with: matchingEmails)
andyvn22
  • 14,696
  • 1
  • 52
  • 74