How to compare nested collections in 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:

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?

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
}

Need Your Help

iframe can't find YouTube videos in HTML

html iframe youtube

For a website I am designing for an assignment about kids films and I thought I would put an iframe in to show the trailer from a YouTube video. This is the code I used (just with a test video);

Why doesn't U-Boot disable the console output

console boot bootloader u-boot silent

I have this system which is accessed by a serial Debug Port. I want to disable all of the output, that was made during the U-Boot boot. Therefore there is the

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.