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 8
In Progress

Swift: intersection Method

Yasin Cakal 28 Dec 2021
Lesson Progress
0% Complete

We can use set operations in Swift to create new sets based on data from two different sets! This comes in handy when working with multiple data sets.

To find matching values in two different sets, we can use the .intersection() method:

var SetIntersection = SetA.intersection(SetB)

  • We add .intersection() to an already existing set.
  • Within the parentheses, we place the second set ().
  • When creating a set via set operations, we do not need to use the Set keyword.

Assume we have the following two sets of names of countries in Southern and Eastern Europe:

var SouthEurope: Set = ["Albania", "Bosnia", "Croatia", "Italy", "Portugal"];
 
var EastEurope: Set = ["Belarus", "Hungary", "Croatia", "Albania", "Poland"];

We can use .intersection() to create a set called AllEurope that contains countries from both European Regions:

var AllEurope = SouthEurope.intersection(EastEurope);

If we use print() to output AllEurope, we get the following result:

["Croatia", "Albania"]

Responses

Leave a Reply

%d bloggers like this: