二元运算符'=='不能应用于两个操作数

Hen*_*Lee 18 enums swift equatable

我有一个协议类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
}
Run Code Online (Sandbox Code Playgroud)

但这给了我错误(见标题).该属性item[[String: String]]以前,没有问题,我不知道如何解决这个问题.我试着谷歌搜索和搜索所有的SO但没有运气..

枚举只是一个简单的基本:

enum Modifications: Int {
    case Add    = 1
    case Remove = 2
    case More   = 3
    case Less   = 4
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 19

更新: SE-0143Swift 4.2中实现了条件一致性.

因此,您的代码现在可以编译.如果你定义Item为一个结构

struct Item: Equatable {
    let item: [[Modifications: String]]

    init(item: [[Modifications: String]]) {
        self.item = item
    }
}
Run Code Online (Sandbox Code Playgroud)

然后编译器==自动合成运算符,比较SE-0185 Synthesizing Equatable和Hashable一致性


(Pre Swift 4.1回答:)

问题是即使==是为字典类型定义的 [Modifications: String],该类型也不符合 Equatable.因此数组比较运算符

public func ==<Element : Equatable>(lhs: [Element], rhs: [Element]) -> Bool
Run Code Online (Sandbox Code Playgroud)

无法应用[[Modifications: String]].

一种可能的简洁实现==Item

func ==(lhs: Item, rhs: Item) -> Bool {
    return lhs.item.count == rhs.item.count 
           && !zip(lhs.item, rhs.item).contains {$0 != $1 }
}
Run Code Online (Sandbox Code Playgroud)

您的代码编译[[String: String]]- 如果导入了Foundation框架,正如@ user3441734正确地说 - 因为然后[String: String]自动转换为NSDictionary符合的 框架Equatable.以下是该声明的"证据":

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]]() )
Run Code Online (Sandbox Code Playgroud)