user3179636 user3179636 - 1 year ago 152
Swift Question

Swift Array intersection by property

I am trying compare two arrays. One array is an array of

objects, each of which has an
property that is a
email address. The other array is an
object which has a descriptive word like "work" or "personal" and the actual
email address.

Basically both objects have a
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
loops as shown below but that is taking too long.

for person in self.allPeople! {
for e in EmailAddresses! {
if e.value == {
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 Source

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 { $ })
let matchingEmails = EmailAddresses!.map { $0.value }
return !personEmails.isDisjoint(with: matchingEmails)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download