I am using Swift and have two sets, say:
var setA: set<Int>
var setB: set<Int>
How to compare these two sets to see if they are identical (having the same elements regardless of the order)?
Check if two sets are equalSwift provide an == operator. This operator is used to check if both the sets are equal or not. This operator will return true if both the sets are equal. Or it will return false if both the sets are not equal.
The difference between == and === in Swift is: == checks if two values are equal. === checks if two objects refer to the same object.
To check if two arrays are equal in Swift, use Equal To == operator. Equal To operator returns a Boolean value indicating whether two arrays contain the same elements in the same order. If two arrays are equal, then the operator returns true , or else it returns false .
A set is a collection of unique elements. By unique, we mean no two elements in a set can be equal. Unlike sets in C++, elements of a set in Swift are not arranged in any particular order. Internally, A set in Swift uses a hash table to store elements in the set.
Set
conforms to Equatable
, so you can just do this:
if setA == setB {
...
}
"a set A is a subset of a set B, or equivalently B is a superset of A, if A is "contained" inside B, that is, all elements of A are also elements of B. A and B may coincide."
There fore you could check if A is a subset of B and vise versa.
let abcSet: Set = ["Chips", "Sandwiches", "Salad"]
var foodSet = Set(["Salad", "Chips", "Sandwiches"])
abcSet.isSubsetOf(foodSet); // true
foodSet.isSubsetOf(abcSet); // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With