Swift Set formIntersection()

In this tutorial, we will learn about the Swift Set formIntersection() method with the help of examples.

The formIntersection() method removes the elements of the set that aren't also in the given sequence.

Example

// create a set A
var A: Set = [2, 3, 5]

// create an array B
 var B = [2, 4, 6]

// form intersection between set A and array B A.formIntersection(B)
print(A) // Output: [2]

formIntersection() Syntax

The syntax of the set formIntersection() method is:

set.formIntersection(otherSequence)

Here, set is an object of the Set class.


formIntersection() Parameters

The formIntersection() method takes a single parameter:

  • otherSequence - The sequence (mostly arrays and sets) of elements.

Note: The other must be a finite set.


formIntersection() Return Value

  • The formIntersection() method doesn't return any value.

Example: Swift Set formIntersection()

// create a set A
var A: Set = ["a", "c", "d"]

// create another set B
var B: Set = ["c", "b", "e" ]

// create an array C
var C = ["b", "c", "d"]

// form intersection between set A and set B A.formIntersection(B)
print("New A:", A)
// form intersection between array C and set B B.formIntersection(C)
print("New B:", B)

Output

New A: ["c"]
New B: ["c", "b"]

Here, we have used the formIntersection() method to remove the elements that aren't common to both set and the given sequence and finally print the newly updated sets A and B.

Did you find this article helpful?