Swift – Check if this Set is Subset of Another Set

This Set is said to be a subset of another Set, if all the element of this Set are present in another Set.

To check if two a Set is subset of another Set in Swift, call Set.isSubset() method on this Set and pass another Set as argument. isSubset() returns true if all elements of this set are present in another Set, else, it returns false.

Examples

In the following example, we take two sets: set1 and set2. We shall check if set2 is a subset of set1 using isSubset() method.

main.swift

let set1: Set = [2, 4, 6, 8, 10]
let set2: Set = [4, 10]

if set2.isSubset(of: set1) {
    print("set2 is a subset of set1.")
} else {
    print("set2 is not a subset of set1.")
}

Output

set2 is a subset of set1.
Program ended with exit code: 0

Now, let us take elements in the set2, such that set2 is not a subset of set1, and observe the output.

main.swift

let set1: Set = [2, 4, 6, 8, 10]
let set2: Set = [4, 3, 5]

if set2.isSubset(of: set1) {
    print("set2 is a subset of set1.")
} else {
    print("set2 is not a subset of set1.")
}

Output

set2 is not a subset of set1.
Program ended with exit code: 0
ADVERTISEMENT

Conclusion

In this Swift Tutorial, we learned how to check if a given Set is a subset of another Set using Set.isSubset() method.