Back to Course

Introduction to Swift

0% Complete
0/0 Steps
  1. Swift: Basics
    4 Topics
    |
    5 Quizzes
  2. Swift: Variables
    7 Topics
    |
    8 Quizzes
  3. Swift: Conditional Statements
    10 Topics
    |
    11 Quizzes
  4. Swift: Loops
    9 Topics
    |
    10 Quizzes
  5. Swift: Logical Operators
    6 Topics
    |
    7 Quizzes
  6. Swift: Arrays
    8 Topics
    |
    9 Quizzes
  7. Swift: Sets
    11 Topics
    |
    12 Quizzes
  8. Swift: Dictionaries
    11 Topics
    |
    12 Quizzes
  9. Swift: Functions
    13 Topics
    |
    14 Quizzes
  10. Swift: Structures
    11 Topics
    |
    12 Quizzes
  11. Swift: Classes
    7 Topics
    |
    8 Quizzes
Lesson 7, Topic 9
In Progress

Swift: union Method

Yasin Cakal 28 Dec 2021
Lesson Progress
0% Complete

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

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.

Responses

Leave a Reply

%d bloggers like this: