Swift Set formUnion()

The formUnion() method inserts the element of the given sequence into the set.

Example

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

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

// form union between set A and array B A.formUnion(B)
print(A) // Output: [5, 3, 2, 6, 4]

formUnion() Syntax

The syntax of the set formUnion() method is:

set.formUnion(otherSequence)

Here, set is an object of the Set class.


formUnion() Parameters

The formUnion() method takes a single parameter:

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

Note: The other must be a finite set.


formUnion() Return Value

  • The formUnion() method doesn't return any value. It inserts the elements of the given sequence into the set.

Example: Swift Set formUnion()

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

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

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

// insert set B elements into set A A.formUnion(B)
print("New A:", A)
// insert array C elements into set B B.formUnion(C)
print("New B:", B)

Output

New A: ["d", "a", "e", "c"]
New B: ["c", "d", "e", "b"]

Here, we have used the formUnion() method to insert elements of set B and array C into set A and set B respectively.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges