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

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

    If elements of your arrays are conforming to Hashable you can try to use the bag (it's like a set with the registration of each item amount). Here I will use a simplified version of this data structure based on Dictionary. This extension helps to create bag from array of Hashable:

    extension Array where Element: Hashable {
        var asBag: [Element: Int] {
            return reduce(into: [:]) {
                $0.updateValue(($0[$1] ?? 0) + 1, forKey: $1)
            }
        }
    }
    

    Now you need to generate 2 bags from initial arrays and compare them. I wrapped it in this extension:

    extension Array where Element: Hashable {
        func containSameElements(_ array: [Element]) -> Bool {
            let selfAsBag = asBag
            let arrayAsBag = array.asBag
            return selfAsBag.count == arrayAsBag.count && selfAsBag.allSatisfy {
                arrayAsBag[$0.key] == $0.value
            }
        }
    }
    

    This solution was tested with Swift 4.2/Xcode 10. If your current Xcode version is prior to 10.0 you can find the function allSatisfy of ArraySlice in Xcode9to10Preparation. You can install this library with CocoaPods.

提交回复
热议问题