Swift Set intersection()

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

Example


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()

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

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.