Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if two sets are identical in Swift?

Tags:

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)?

like image 950
Joe Huang Avatar asked Apr 02 '16 06:04

Joe Huang


People also ask

How do you check if two sets are equal in Swift?

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.

What is the difference between == and === in Swift?

The difference between == and === in Swift is: == checks if two values are equal. === checks if two objects refer to the same object.

How do I check if two arrays are the same in Swift?

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 .

How SET works internally Swift?

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.


Video Answer


2 Answers

Set conforms to Equatable, so you can just do this:

if setA == setB {
    ...
}
like image 188
rob mayoff Avatar answered Sep 29 '22 13:09

rob mayoff


"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
like image 21
Kalenda Avatar answered Sep 29 '22 11:09

Kalenda