无法应用 Swift 3.0 二元运算符“==" [英] Swift 3.0 binary operator '==' cannot be applied
问题描述
在 Swift 3.0 中,当我尝试比较 [[String: AnyObject]]
和 [[String: AnyObject]] 类型的两个项目时,我遇到了一个奇怪的错误!代码>.所以其中一个是强制展开的,另一个不是.
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.
所以比较如下:
let smth: [[String: AnyObject]] = [["key": "Value"]]
let smth2: [[String: AnyObject]]? = someFunctionThatReturnsAnOptionalArrayOfDictionaries()
if smth == smth2! {
print("Equal")
}
错误说:二元运算符=="不能应用于[[String : AnyObject]]"和[[String : AnyObject]]!"类型的操作数
在 Swift 3 中执行此操作的正确方法是什么?
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).
您可能面临的另一个问题是可选和非可选的比较,这在 Swift 3 中已被删除(仅适用于 <
和 >
,==
和 !=
仍然有效!):
Another problem you could be facing is optional and non-optional comparisons, which was removed in Swift 3 (only for <
and >
, ==
and !=
still work!):
我所做的工作是首先用 if let
解开可选项,然后我将它们与 elementsEqual
进行比较,首先是数组,然后是字典.
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")
}
另一个问题是,由于您使用 AnyObject
作为值,因此无法直接比较它们.这就是为什么我使用 ===
来检查比较对象的引用是否相同.不确定这是否是您想要的.
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.
这篇关于无法应用 Swift 3.0 二元运算符“=="的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!