how to check if a set is a superset of another set in swift

To check if a set is a superset of another set in Swift, we can use the isSuperset(of:) method. This method returns a boolean value indicating whether the set is a superset of the given set. Here's an example:

main.swift
let set1: Set<Int> = [1, 2, 3, 4, 5]
let set2: Set<Int> = [1, 3, 5]

if set1.isSuperset(of: set2) {
    print("set1 is a superset of set2")
} else {
    print("set1 is not a superset of set2")
}
195 chars
9 lines

In this example, set1 is a superset of set2 because it contains all the elements in set2. The isSuperset(of:) method returns true, so the output is "set1 is a superset of set2".

We can also use the isSubset(of:) method to check if a set is a subset of another set. This method works in the opposite way - it returns a boolean value indicating whether the set is a subset of the given set.

main.swift
let set1: Set<Int> = [1, 2, 3, 4, 5]
let set2: Set<Int> = [1, 3, 5]

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

In this example, set2 is a subset of set1 because all the elements in set2 are also in set1. The isSubset(of:) method returns true, so the output is "set2 is a subset of set1".

gistlibby LogSnag