Swift: union Method

union Method of Swift’s Set:

Let’s discuss union method of set in Swift.

We can also use .union() as a set operation. By combining the values of two sets, this operation generates a set in Swift.

The following is the syntax for creating a set with .union():

var NewSet = SetA.union(SetB)

Consider the following Basket1 and Basket2 sets, which contain different things:

var Basket1: Set = ["Chips", "Cold Drink", "Chocolate", "Juice"];
var Basket2: Set = ["Cake", "Juice", "Fruits"];

We can use .union() to group all of the things together into a single set called Basket:

var Basket = Basket1.union(Basket2);

Suppose you find a third basket, Basket3:

var Basket3: Set = ["Vegetables", "Water"];

We can combine multiple sets using set operations, as shown below:

var Basket = Basket1.union(Basket2).union(Basket3);

Method chaining is the use of multiple methods in the same line of code.

When we print Basket, we get something like this:

["Chocolate", "Fruits", "Water", "Juice", "Cake", "Chips", "Vegetables", "Cold Drink"]

The element “Juice” appeared in both Basket1 and Basket2; however, because sets only contain unique elements, it only appears once in Basket.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: