如何检查Swift中的两个集合是否相同?

时间:2016-04-02 06:34:19

标签: swift swift2 set

我正在使用Swift,有两套,比如说:

var setA: set<Int>
var setB: set<Int>

如何比较这两组以确定它们是否相同(无论顺序如何都具有相同的元素)?

2 个答案:

答案 0 :(得分:16)

Swift的Set符合Equatable协议(符合HashableEquatable的子协议。所以你可以这样做:

if setA == setB {
    ...
}

答案 1 :(得分:4)

"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."

因此,您可以检查A是否是B的子集,反之亦然。

let abcSet: Set = ["Chips", "Sandwiches", "Salad"]
var foodSet = Set(["Salad", "Chips", "Sandwiches"])


abcSet.isSubsetOf(foodSet); // true
foodSet.isSubsetOf(abcSet); // true