# Checking if two sets have elements in common

**URL:** <https://forums.swift.org/t/checking-if-two-sets-have-elements-in-common/64491>\
**Category:** Pitches\
**Tags:** set-collection\
**Created:** [April 19, 2023, 5:49pm UTC](https://forums.swift.org/t/checking-if-two-sets-have-elements-in-common/64491 "2023-04-19T17:49:26Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [April 19, 2023, 5:49pm UTC](https://forums.swift.org/t/checking-if-two-sets-have-elements-in-common/64491/1 "2023-04-19T17:49:27Z")

</div>

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

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

```

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

```swift
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.

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [April 19, 2023, 6:17pm UTC](https://forums.swift.org/t/checking-if-two-sets-have-elements-in-common/64491/3 "2023-04-19T18:17:30Z")

</div>

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