Swift 3.0 binary operator '==' cannot be a

2019-05-28 19:59发布

In Swift 3.0 I'm getting a weird error when I try to compare two items which are of type [[String: AnyObject]] and [[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! {
    print("Equal")
}

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?

标签: swift swift3
2条回答
虎瘦雄心在
2楼-- · 2019-05-28 20:18

This SO answer includes a solution to this problem under the sub-heading 'Xcode 8 beta 6 • Swift 3'.

Note in particular:

In the example above all dictionary keys and values are the same type. If we try to compare two dictionaries of type [String: Any] Xcode will complain that Binary operator == cannot be applied to two [String: Any] operands. ... But we can extend the == operator functionality using the NSDictionary initializer:

查看更多
戒情不戒烟
3楼-- · 2019-05-28 20:21

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
    }

}) {
    print("Equal")
}

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.

查看更多
登录 后发表回答