Find whether two Swift Arrays contain the same elements

前端 未结 3 554
清歌不尽
清歌不尽 2020-12-22 11:41

I have two arrays

let a1 = [obj1, obj2, obj3]
let a2 = [obj3, obj2, obj1]

Assume that the array elements are custom objects which are

3条回答
  •  太阳男子
    2020-12-22 12:12

    You can convert them into Set or NSSet instances which are unsorted by definition and compare those. Better yet, instead of using arrays at all, consider using sets in the first place.

    let a1 = [1, 4, 5]
    let a2 = [4, 5, 1]
    let s1 = NSSet(array: a1)
    let s2 = NSSet(array: a2)
    print(s1 == s2) // Prints "true"
    

    If objects may appear multiple times in your arrays, you need to use a NSCountedSet instead which also counts how often each object occurs in a set:

    let a1 = [1, 1, 2]
    let a2 = [1, 2, 2]
    
    let s1 = NSSet(array: a1)
    let s2 = NSSet(array: a2)
    print(s1 == s2) // Prints "true"
    
    let c1 = NSCountedSet(array: a1)
    let c2 = NSCountedSet(array: a2)
    print(c1 == c2) // Prints "false"
    

提交回复
热议问题