Check if elements in two arrays are same irrespect

2019-03-06 03:21发布

问题:

Suppose if I have two arrays - array1 and array2

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

Then I want result as array1 is equal to array2.

Also if my array has duplicate elements

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

Then I want result as array1 is NOT equal to array2.

after searching I have found Compare two arrays with the same value but with a different order

but it is in Objective C and isEqualToSetis not there in Swift3

回答1:

Using counted sets as in Compare two arrays with the same value but with a different order works in Swift as well:

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

This works well for strings, numbers, and other values which are mapped to corresponding Foundation types NSString, NSNumber, etc. It might give unexpected results when used with custom structs.

For a pure Swift solution, count the number of occurrences of each element in the arrays:

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

and compare the resulting dictionaries:

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

Alternatively – if the array elements are Comparable – compare the sorted arrays:

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


回答2:

You can do the same thing in Swift using Set and the == operator.