Sling Academy
Home/Swift/How to Find the Intersection of 2 Sets in Swift

How to Find the Intersection of 2 Sets in Swift

Last updated: May 11, 2023

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.

Next Article: How to Find the Union of 2 Sets in Swift

Previous Article: Subtracting 2 Sets in Swift (with Examples)

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)
  • Swift: 5 Ways to Iterate over an Array