Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare nested collections in swift

Tags:

swift

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:

enter image description here

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?

like image 395
Saltymule Avatar asked Sep 25 '14 12:09

Saltymule


1 Answers

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
}
like image 190
Nate Cook Avatar answered Oct 16 '22 10:10

Nate Cook