【问题标题】:How to check if two sets are identical in Swift?如何在 Swift 中检查两个集合是否相同?
【发布时间】:2016-04-02 06:34:19
【问题描述】:

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

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

如何比较这两个集合,看它们是否相同(无论顺序如何,都具有相同的元素)?

【问题讨论】:

    标签: swift swift2 set


    【解决方案1】:

    Set conformsEquatable,所以你可以这样做:

    if setA == setB {
        ...
    }
    

    【讨论】:

    • Swift 5 还是这样吗?
    • @BradThomas 是的。
    【解决方案2】:

    "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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2011-06-22
      • 2014-06-11
      相关资源
      最近更新 更多