bubakazouba bubakazouba - 2 months ago 31x
Swift Question

how do I compare two dictionaries in swift?

is there an easy way to compare two dictionaries [String: AnyObject] in swift, since it doesn't accept the


by comparing two dictionaries I mean checking that they have the same exact keys and for every key they have the same values.


As already mentioned by Hot Licks you can use NSDictionary method isEqualToDictionary() to check if they are equal as follow:

let dic1: [String: AnyObject] = ["key1": 100, "key2": 200]
let dic2: [String: AnyObject] = ["key1": 100, "key2": 200]
let dic3: [String: AnyObject] = ["key1": 100, "key2": 250]

println( NSDictionary(dictionary: dic1).isEqualToDictionary(dic2) )   // true
println( NSDictionary(dictionary: dic1).isEqualToDictionary(dic3) )  // false

you can also implement a custom operator "==" as follow:

public func ==(lhs: [String: AnyObject], rhs: [String: AnyObject] ) -> Bool {
    return NSDictionary(dictionary: lhs).isEqualToDictionary(rhs)

println(dic1 == dic2)   // true
println(dic1 == dic3)   // false