Swift: intersection Method

intersection Method of Swift’s Set:

We can use set operations in Swift programming language to create new sets based on data from two different sets! This comes in handy when working with multiple data sets. Let’s discuss intersection method of set in Swift.

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"]

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: