In Swift, you can find the intersection of two sets using the intersection method.
In this example,
set1
and set2
, using Swift's Set data structure.intersection
method to find the common elements between set1
and set2
.intersection
.intersection
to display the intersection of the two sets.let set1: Set<Int> = [1, 2, 3, 4]
let set2: Set<Int> = [3, 4, 5, 6]
let intersection = set1.intersection(set2)
print("Intersection of set1 and set2:")
intersection.forEach { print($0) }
Intersection of set1 and set2: 3 4
In this example,
set1
and set2
, using Swift's Set data structure and add elements to them.findIntersection
that takes two sets as input parameters.findIntersection
function, we use the filter
method to filter elements from set1
that are present in set2
.let set1: Set<Int> = [1, 2, 3, 4]
let set2: Set<Int> = [3, 4, 5, 6]
func findIntersection(set1: Set<Int>, set2: Set<Int>) -> Set<Int> {
return Set(set1.filter { set2.contains($0) })
}
let intersection = findIntersection(set1: set1, set2: set2)
print("Intersection of set1 and set2:")
intersection.forEach { print($0) }
Intersection of set1 and set2: 3 4
In this tutorial, we learned How to find Intersection of Two Sets in Swift language with well detailed examples.