user3179636 user3179636 - 4 months ago 16
Swift Question

Swift Array intersection by property

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.

Answer

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)