Check if elements in two arrays are same irrespective of index

前端 未结 2 1374
失恋的感觉
失恋的感觉 2021-01-26 01:01

Suppose if I have two arrays - array1 and array2

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


        
2条回答
  •  旧时难觅i
    2021-01-26 01:44

    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(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())
    

提交回复
热议问题