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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With