Swift – Check if this Set is Superset of Another Set
This Set is said to be a superset of another Set, if all the element of another Set are present in this Set.
To check if two a Set is superset of another Set in Swift, call Set.isSuperset() method on this Set and pass another Set as argument. isSuperset() returns true if all elements of another set are present in this Set, else, it returns false.
Examples
In the following example, we take two sets: set1
and set2
. We shall check if set1
is a superset of set2
using isSuperset() method.
main.swift
</>
Copy
let set1: Set = [2, 4, 6, 8, 10]
let set2: Set = [4, 10]
if set1.isSuperset(of: set2) {
print("set1 is a superset of set2.")
} else {
print("set1 is not a superset of set2.")
}
Output
set1 is a superset of set2.
Program ended with exit code: 0
Now, let us take elements in the set2
, such that set1
is not a superset of set2
, and observe the output.
main.swift
</>
Copy
let set1: Set = [2, 4, 6, 8, 10]
let set2: Set = [4, 5, 3]
if set1.isSuperset(of: set2) {
print("set1 is a superset of set2.")
} else {
print("set1 is not a superset of set2.")
}
Output
set1 is not a superset of set2.
Program ended with exit code: 0
Conclusion
In this Swift Tutorial, we learned how to check if a given Set is a superset of another Set using Set.isSuperset() method.