Swift Set intersection()

The intersection() method returns a new set with elements that are common to both elements.

Example

var A: Set = [2, 3, 5]
var B: Set = [1, 3, 5]

// compute intersection between A and B print("A n B = ", A.intersection(B))
// Output: A n B = [5, 3]

intersection() Syntax

The syntax of the set intersection() method is:

set.intersection(otherSet)

Here, set is an object of the Set class.


intersection() Parameters

The intersection() method takes a single parameter:

  • otherSet - The set of elements.

Note: The other must be a finite set.


intersection() Return Value

  • The intersection() method returns a new set with common elements of set and other (set passed as an argument).

Example 1: Swift Set intersection()

var A: Set = ["a", "c", "d"]
var B: Set = ["c", "b", "e" ]
var C: Set = ["b", "c", "d"]

// compute intersection between A and B print("A n B =", A.intersection(B))
// compute intersection between B and C print("B n C =", B.intersection(C))

Output

A n B = ["c"]
B n C = ["b", "c"]

Here, we have used the intersection() method to compute the intersection between A and B & B and C respectively.


Example 2: Use of Swift intersection() and Ranges

// create a set that ranges from 1 to 4
var total = Set(1...10)

// compute intersection print(total.intersection([5,10,15]))

Output

[10, 5]

Here, 1...10 represents a set of numbers that ranges from 1 to 10 and is assigned to total.

Finally, we have computed the intersection between total and [5,10,15].

Since 5 and 10 are only common, the intersection() method just prints 5 and 10.

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community