How do I check in Swift if two arrays contain the same elements regardless of the order in which those elements appear in?

前端 未结 8 1159
臣服心动
臣服心动 2020-12-02 22:20

Let\'s say there are two arrays...

var array1 = [\"a\", \"b\", \"c\"]
var array2 = [\"b\", \"c\", \"a\"]

I\'d like the result of the compar

相关标签:
8条回答
  • 2020-12-02 22:58

    Using Set

    let array1 = ["a", "b", "c"]
    let array2 = ["b", "c", "a", "c"]
    
    let set1 = Set(array1)
    let set2 = Set(array2)
    
    if (set1.count == set2.count && set1 == set2) { //if you compare big sets it is recommended to compare the count of items in the sets beforehand
        //they are identical
    }
    

    The Set implements Hashable so the task is to implement the hash function to work with a Set

    0 讨论(0)
  • 2020-12-02 22:59

    Swift 3, 4

    extension Array where Element: Comparable {
        func containsSameElements(as other: [Element]) -> Bool {
            return self.count == other.count && self.sorted() == other.sorted()
        }
    }
    
    // usage
    let a: [Int] = [1, 2, 3, 3, 3]
    let b: [Int] = [1, 3, 3, 3, 2]
    let c: [Int] = [1, 2, 2, 3, 3, 3]
    
    print(a.containsSameElements(as: b)) // true
    print(a.containsSameElements(as: c)) // false
    

    0 讨论(0)
提交回复
热议问题