To find the union of two sets in Swift, you can use the union method provided by the Set structure.
In this example,
set1
and set2
, containing some elements.set1
to perform the union operation with set2
.set1
contains all the unique elements from both set1
and set2
.var set1: Set<Int> = [1, 2, 3]
var set2: Set<Int> = [3, 4, 5]
let unionSet = set1.union(set2)
print("Union of set1 and set2:")
for item in unionSet {
print(item)
}
Union of set1 and set2: 5 2 3 1 4
In this example,
set1
and set2
, containing some string elements.set1
to perform the union operation with set2
.set1
contains all the unique elements from both set1
and set2
.var set1: Set<String> = ["apple", "banana", "orange"]
var set2: Set<String> = ["orange", "pear", "grape"]
let unionSet = set1.union(set2)
print("Union of set1 and set2:")
for item in unionSet {
print(item)
}
Union of set1 and set2: orange banana apple grape pear
In this tutorial, we learned How to find Union of Two Sets in Swift language with well detailed examples.