二进制运算符'=='不能应用于两个操作数 [英] Binary operator '==' cannot be applied to two operands

查看:63
本文介绍了二进制运算符'=='不能应用于两个操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用协议 Equatable 的类.该类如下所示:

I have a class with the protocol Equatable. The class looks like this:

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]] ,并且没有问题,我也不知道如何解决此问题.我尝试使用Google搜索和搜索,但是没有运气.

But this is giving me the error (see title). The property item was [[String: String]] before and there was no problem and I have no idea how to fix this. I tried googling and searching all over SO but with no luck..

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

The enum is just a simple basic one:

enum Modifications: Int {
    case Add    = 1
    case Remove = 2
    case More   = 3
    case Less   = 4
}

推荐答案

更新:因此,您的代码现在可以编译.而且,如果您将 Item 定义为 struct

As a consequence, your code does compile now. And if you define Item as a struct

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

    init(item: [[Modifications: String]]) {
        self.item = item
    }
}

然后编译器自动合成 == 运算符,比较 SE-0185合成可量化和可哈希的一致性

then the compiler synthesizes the == operator automatically, compare SE-0185 Synthesizing Equatable and Hashable conformance

(Pre Swift 4.1答案:)

问题在于,即使为字典类型定义了 == [Modifications:String] ,该类型不符合平等.因此,数组比较运算符

The problem is that even if == is defined for the dictionary type [Modifications: String], that type does not conform to Equatable. Therefore the array comparison operator

public func ==<Element : Equatable>(lhs: [Element], rhs: [Element]) -> Bool

不能应用于 [[Modifications:String]] .

对于 Item 来说, == 的一种可能的简洁实现是

A possible concise implementation of == for Item would be

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 平等.这是该声明的证据":


Your code compiles for [[String: String]] – if the Foundation framework is imported, as @user3441734 correctly said – because then [String: String] is automatically converted to NSDictionary which conforms to Equatable. Here is a "proof" for that claim:

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]]() )

这篇关于二进制运算符'=='不能应用于两个操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆