Checking if two sets have elements in common

I had an instance when I was checking if two sets have elements in common:

if !a.intersection(b).isEmpty { ... }

when realised it would work quicker if I do it manually:

extension Set {
    func containsMembers(from other: Set) -> Bool {
        count < other.count ? contains { other.contains($0) } : other.contains { contains($0) }
    }
}

As it would avoid making the intersection first (memory allocation and carefully calculating the whole subset of elements in common even when we know that a single common element is enough to know the outcome).

Could be a little but handy addition to the standard library.

Nice, thank you. Also the name "intersects" is spot-on.

2 Likes