Suppose if I have two arrays - array1
and array2
let array1 = [\"abc\",\"pqr\",\"xyz\"]
let array2 = [\"pqr\", \"xyz\", \"abc\"]
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())
You can do the same thing in Swift using Set
and the ==
operator.