how to get the intersection of two sets in swift

To get the intersection of two sets in Swift, you can use the intersection method. This method returns a new set that contains only the elements that are common to both sets.

main.swift
let setA: Set<Int> = [1, 2, 3, 4, 5]
let setB: Set<Int> = [3, 4, 5, 6, 7]

let intersection = setA.intersection(setB) // [3, 4, 5]
131 chars
5 lines

In the code above, setA and setB are two sets of Integers. We call the intersection method on setA passing setB as an argument. The resulting set intersection will contain the elements that are common to both sets, which in this case are 3, 4, and 5.

related categories

gistlibby LogSnag