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

前端 未结 8 1207
臣服心动
臣服心动 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:56

    Solution for Swift 4.1/Xcode 9.4:

    extension Array where Element: Equatable {
        func containSameElements(_ array: [Element]) -> Bool {
            var selfCopy = self
            var secondArrayCopy = array
            while let currentItem = selfCopy.popLast() {
                if let indexOfCurrentItem = secondArrayCopy.index(of: currentItem) {
                    secondArrayCopy.remove(at: indexOfCurrentItem)
                } else {
                    return false
                }
            }
            return secondArrayCopy.isEmpty
        }
    }
    

    The main advantage of this solution is that it uses less memory than other (it always creates just 2 temporary arrays). Also, it does not require for Element to be Comparable, just to be Equatable.

提交回复
热议问题