How to Find the Intersection of 2 Sets in Swift

Updated: May 11, 2023 By: Khue Post a comment

This concise and straight-to-the-point article is about finding the intersection of 2 sets in Swift. I assume you already have some basic understanding of the programming language, so I won’t waste your time by explaining what Swift is or talking about its history.

The intersection of two sets is a new set that contains all the elements that are common to both sets. Swift provides a built-in method called intersection() that can help you painlessly get the intersection of two sets with just a single line of code:

result = set1.intersection(set2)

Let’s examine a practical example for more clarity. Let’s say you have a set that stores the names of your friends and another set that stores the names of your colleagues. What you want to find out is a set that contains the names of people in which each person is both your friend and your colleague.

let friends: Set<String> = ["Pam", "Jim", "Andy", "Darryl"]
let colleagues: Set<String> = ["Dwight", "Michael", "Kelly", "Andy", "Darryl"]

let workFriends: Set<String> = friends.intersection(colleagues)

print(workFriends)

Output:

["Darryl", "Andy"]

The above is just a simplified example. We assume that in each set of friends/ colleagues there are no 2 people with the same name.