Learn
In Swift, we can use set operations to create new sets based on the data within two different sets! This is useful when we are working with multiple data sets.
We can use the .intersection()
method to find matching values in two different sets:
var newSet = SetA.intersection(SetB)
- We append
.intersection()
to an existing set. - We place the second set inside the parentheses
()
. - We do not need to use the
Set
keyword when creating a set via set operations.
Letβs say we had the following two sets that contain the names of continents in the northern and southern hemisphere:
var northHemisphere: Set = ["South America", "Europe", "North America", "Africa", "Asia"] var southHemisphere: Set = ["Australia", "Antarctica", "Africa", "South America", "Asia"]
We can use .intersection()
to create a set called bothHemispheres
that contains continents that exist in both hemispheres:
var bothHemispheres = northHemisphere.intersection(southHemisphere)
If we use print()
to output bothHemispheres
, we would get this result:
["Asia", "South America", "Africa"]
Instructions
1.
In Animals.swift we have two sets: swim
and fly
.
Use .intersection()
to create a set called swimAndFly
that contains the shared values of swim
and fly
.
Use print()
to output swimAndFly
.
Take this course for free
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.