I have two collections:
let collection1:[String:[String:NSObject]] = ["somekey":["nestedkey":"value"]]
let collection2:[String:[String:NSObject]] = ["somekey":["nestedkey":"value"]]
//I would like to compare them using the following:
let collectionsAreEqual = collection1 == collection2
Copying and pasting the above code into a playground gives the following error:
I know I can write an equal function for this:
infix func == (this:[String:[String:NSObject]], that:[String:[String:NSObject]]){
//return true or false
}
In objective c, isEqual: on an NSDictionary handles this no problem, because it does the nested comparison for you. Is there some method of generally handling this in swift?
Update
I can use the following:
//:[String:[String:NSObject]]
let collection1:[String:NSObject] = ["somekey":["nestedkey":"value"]]
let collection2:[String:NSObject] = ["somekey":["nestedkey":"value"]]
//I would like to compare them using the following:
let collectionsAreEqual = collection1 == collection2
but it requires using NSObject as the value in the declaration. Is there a pure swift method to handle this?
Here's an equality operator that will compare any two nested dictionaries with the same type:
func ==<T: Equatable, K1: Hashable, K2: Hashable>(lhs: [K1: [K2: T]], rhs: [K1: [K2: T]]) -> Bool {
if lhs.count != rhs.count { return false }
for (key, lhsub) in lhs {
if let rhsub = rhs[key] {
if lhsub != rhsub {
return false
}
} else {
return false
}
}
return true
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With