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

To check if a set is a subset of another set in Swift, you can use the isSubset(of:) method. This method returns a Boolean value indicating whether the set is a subset of the specified set.

Here's an example:

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

if setB.isSubset(of: setA) {
    print("setB is a subset of setA")
} else {
    print("setB is not a subset of setA")
}
183 chars
9 lines

In this example, we have two sets setA and setB. We check if setB is a subset of setA using the isSubset(of:) method. Since setB contains 2 and 3, which are also present in setA, the method returns true and the output is "setB is a subset of setA".

If setB had contained an element that was not present in setA, the method would have returned false instead.

related categories

gistlibby LogSnag