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

标签 swift enums equatable

我有一个使用协议(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/

相关文章:

swift:为什么重载 "=="运算符时需要符合 equatable?

swift - 当我的应用程序状态为后台时,pushkit 会发送通知。如何使应用程序状态变为事件状态?

在 ForEach 中删除数组元素时,SwiftUI 没有索引

c# - 如何使用 C# 返回标有自定义属性的枚举值

C# TypeConverter long 到枚举类型在 ChangeType 上失败

swift - 为什么 swift 编译器在有/没有 Equatable 协议(protocol)的情况下对相等运算符的行为不同

Swift 协议(protocol)实现 Equatable

ios - AVCaptureStillImageOutput.pngStillImageNSDataRepresentation?

ios - CoreStore 创建对象并成功返回

c - 枚举值疑惑?