Swift – Find Intersection of Sets

To find intersection of Sets in Swift, call intersection() method on this Set and pass the other set as argument to it. Set.intersection() returns a new Set with the elements common to both the Sets.

Examples

In the following example, we take two Sets: set1 and set2, and find the intersection of these two Sets using intersection() method.

main.swift

</>
Copy
let set1: Set = [2, 4, 6, 8]
let set2: Set = [2, 8, 14, 22]

let result = set1.intersection(set2)

print("Set 1 : \(set1)")
print("Set 2 : \(set2)")
print("Intersection : \(result)")

Output

Set 1 : [4, 6, 2, 8]
Set 2 : [22, 8, 2, 14]
Intersection : [2, 8]
Program ended with exit code: 0

Conclusion

In this Swift Tutorial, we learned how to find intersection of two Sets using Set.intersection() method.