【问题标题】:Check if elements in two arrays are same irrespective of index无论索引如何,检查两个数组中的元素是否相同
【发布时间】:2016-11-30 08:46:58
【问题描述】:

假设我有两个数组 - array1array2

let array1 = ["abc","pqr","xyz"]
let array2 = ["pqr", "xyz", "abc"]

然后我想要结果,因为 array1 等于 array2。

如果我的数组有重复的元素

let array1 = ["abc","pqr","xyz"]
let array2 = ["pqr", "xyz", "abc", "abc", "xyz"]

然后我想要结果,因为 array1 不等于 array2。

搜索后发现Compare two arrays with the same value but with a different order

但它在 Objective C 中,而isEqualToSet在 Swift3 中不存在

【问题讨论】:

    标签: arrays swift set swift3


    【解决方案1】:

    在 Swift 中使用 Compare two arrays with the same value but with a different order 中的计数集 还有:

    let set1 = NSCountedSet(array: array1)
    let set2 = NSCountedSet(array: array2)
    print(set1 == set2)
    

    这适用于字符串、数字和其他值 映射到相应的 Foundation 类型 NSStringNSNumber 等。 与自定义结构一起使用时,它可能会产生意想不到的结果。

    对于纯 Swift 解决方案,计算每个的出现次数 数组中的元素:

    func countMap<T: Hashable>(array: [T]) -> [T: Int] {
        var dict = [T: Int]()
        for elem in array {
            dict[elem] = (dict[elem] ?? 0) + 1
        }
        return dict
    }
    

    并比较结果字典:

    print(countMap(array: array1) == countMap(array: array2))
    

    或者——如果数组元素是Comparable—— 比较排序后的数组:

    print(array1.sorted() == array2.sorted())
    

    【讨论】:

      【解决方案2】:

      您可以在 Swift 中使用 Set== 运算符来做同样的事情。

      【讨论】:

        猜你喜欢
        • 2022-12-12
        • 1970-01-01
        • 2014-07-29
        • 1970-01-01
        • 1970-01-01
        • 2012-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多