我有一个使用协议(protocol) Equatable
的类。该类看起来像这样:
class Item: Equatable {
let item: [[Modifications: String]]
init(item: [[Modifications: String]]) {
self.item = item
}
}
func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.item == rhs.item
}
但这给了我错误(见标题)。属性 item
之前是 [[String: String]]
并且没有问题,我不知道如何解决这个问题。我尝试在整个 SO 上进行谷歌搜索和搜索,但没有运气......
枚举只是一个简单的基本枚举:
enum Modifications: Int {
case Add = 1
case Remove = 2
case More = 3
case Less = 4
}
最佳答案
更新: SE-0143 Conditional conformances已在 Swift 4.2 中实现。
因此,您的代码现在可以编译了。如果您将 Item
定义为 struct
struct Item: Equatable {
let item: [[Modifications: String]]
init(item: [[Modifications: String]]) {
self.item = item
}
}
然后编译器自动合成==
操作符,
比较 SE-0185 Synthesizing Equatable and Hashable conformance
(Swift 4.1 之前的回答:)
问题是即使==
定义为字典类型
[Modifications: String]
,那个类型不符合
平等
。因此数组比较运算符
public func ==<Element : Equatable>(lhs: [Element], rhs: [Element]) -> Bool
不能应用于 [[Modifications: String]]
。
对于 Item
的 ==
可能的简洁实现是
func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.item.count == rhs.item.count
&& !zip(lhs.item, rhs.item).contains {$0 != $1 }
}
你的代码为 [[String: String]]
编译——如果基金会
框架被导入,如@user3441734 正确所说 - 因为 [String: String]
会自动转换为 NSDictionary
,它符合
平等
。这是该声明的“证据”:
func foo<T : Equatable>(obj :[T]) {
print(obj.dynamicType)
}
// This does not compile:
foo( [[Modifications: String]]() )
// This compiles, and the output is "Array<NSDictionary>":
foo( [[String: String]]() )
关于swift - 二元运算符 '==' 不能应用于两个操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34640685/