Majster Majster - 5 months ago 160
Swift Question

Swift 3.0 binary operator '==' cannot be applied

In Swift 3.0 I'm getting a weird error when I try to compare two items which are of type

[[String: AnyObject]]
[[String: AnyObject]]!
. So one of them is force unwrapped and the other is not.

So the comparison looks like:

let smth: [[String: AnyObject]] = [["key": "Value"]]
let smth2: [[String: AnyObject]]? = someFunctionThatReturnsAnOptionalArrayOfDictionaries()

if smth == smth2! {

The error says:
Binary operator '==' cannot be applied to operands of type '[[String : AnyObject]]' and '[[String : AnyObject]]!'

What is the correct way to do this in Swift 3?


It is a little tricky, since you can't directly compare arrays or dictionaries (without overloading operators).

Another problem you could be facing is optional and non-optional comparisons, which was removed in Swift 3 (only for < and >, == and  != still work!):

Swift Evolution - Proposal #0121

What I did to make it work was first unwrap the optional with if let then I compared them with elementsEqual, first the array, then the dictionary.

let smth: [[String: AnyObject]] = [["key": "Value" as AnyObject]]
let smth2: [[String: AnyObject]]?  = nil

if let smth2 = smth2, smth.elementsEqual(smth2, by: { (obj1, obj2) -> Bool in
    return obj1.elementsEqual(obj2) { (elt1, elt2) -> Bool in
        return elt1.key == elt2.key && elt1.value === elt2.value

}) {

Another problem is, since you are using AnyObject as value, you can't compare them directly. Thats why I used === which checks if the reference of comparing objects is the same. Not sure if this is what you wanted.