Swift – Check if Two Sets are Equal

Two Sets are said to be equal if they contain equal elements.

To check if two Sets are equal in Swift, use Equal To comparison operator and pass the Sets as operands. The operator returns true if the given Sets are equal, else, it returns false.

Examples

In the following example, we take two sets: set1 and set2. Using Equal To operator, we shall check if these two sets are equal.

main.swift

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

if set1 == set2 {
    print("The two sets are equal.")
} else {
    print("The two sets are not equal.")
}

Output

The two sets are equal.
Program ended with exit code: 0

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

main.swift

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

if set1 == set2 {
    print("The two sets are equal.")
} else {
    print("The two sets are not equal.")
}

Output

The two sets are not equal.
Program ended with exit code: 0
ADVERTISEMENT

Conclusion

In this Swift Tutorial, we learned how to check if two Sets are equal using Equal To operator.