Swift – Check if Two Sets are Disjoint

Two Sets are said to be disjoint if they have no element in common.

To check if two Sets are disjoint in Swift, call isDisjoint() method on this Set, and pass another Set as argument. The method returns true if the given Sets are disjoint, else, it returns false.

Examples

In the following example, we take two sets: set1 and set2 and check if set1 is disjoint with set2.

main.swift

</>
Copy
let set1: Set = [2, 4, 6, 8, 10]
let set2: Set = [1, 5, 3]

if set1.isDisjoint(with: set2) {
    print("set1 is disjoint with set2.")
} else {
    print("set1 is not disjoint with set2.")
}

Output

set1 is disjoint with set2.
Program ended with exit code: 0

Now, let us take elements in the Sets, such that they are not disjoint, and observe the output.

main.swift

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

if set1.isDisjoint(with: set2) {
    print("set1 is disjoint with set2.")
} else {
    print("set1 is not disjoint with set2.")
}

Output

set1 is not disjoint with set2.
Program ended with exit code: 0

Conclusion

In this Swift Tutorial, we learned how to check if two Sets are disjoint using Set.isDisjoint() method.