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

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

    Here is a solution that does not require the element to be Comparable, but only Equatable. It is much less efficient than the sorting answers, so if your type can be made Comparable, use one of those.

    extension Array where Element: Equatable {
        func equalContents(to other: [Element]) -> Bool {
            guard self.count == other.count else {return false}
            for e in self{
              guard self.filter{$0==e}.count == other.filter{$0==e}.count else {
                return false
              }
            }
            return true
        }
    }
    

提交回复
热议问题