检查两个数组中的元素是否相同,与索引无关 [英] Check if elements in two arrays are same irrespective of index
问题描述
假设我有两个数组-array1
和array2
Suppose if I have two arrays - array1
and array2
let array1 = ["abc","pqr","xyz"]
let array2 = ["pqr", "xyz", "abc"]
然后我想要结果为array1等于array2.
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"]
然后我想要结果为array1不等于array2.
Then I want result as array1 is NOT equal to array2.
搜索后,我发现但是它在目标C中,而isEqualToSet
在Swift3中不存在
but it is in Objective C and isEqualToSet
is not there in Swift3
推荐答案
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)
这对于字符串,数字和其他值非常有效
映射到相应的Foundation类型NSString
,NSNumber
等.
与自定义结构一起使用时,可能会产生意想不到的结果.
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.
对于纯Swift解决方案,计算每个出现的次数 数组中的元素:
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
}
并比较结果字典:
print(countMap(array: array1) == countMap(array: array2))
或者–如果数组元素为Comparable
–
比较排序后的数组:
Alternatively – if the array elements are Comparable
–
compare the sorted arrays:
print(array1.sorted() == array2.sorted())
这篇关于检查两个数组中的元素是否相同,与索引无关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!