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
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.