如何解决“二元运算符”=='不能应用于两个'Foo'操作数“? [英] How to resolve "Binary operator '==' cannot be applied to two 'Foo' operands"?
问题描述
我按如下方式创建了一个类Foo:
I created a class Foo as follows:
class Foo{
var randomeVar:String?
func saySomething(){
print("Something")
}
}
我现在想要比较foo的不同实例,如下所示:
I now want to compare different instances of foo as follows:
let foo1 = Foo()
let foo2 = Foo()
if foo1 == foo2{
print("Cool")
}
当我这样做时,遵守二元运算符'=='不能应用于两个'Foo'操作数的投诉。问题是什么以及如何解决?
When I do so however the complies complaints that "Binary operator '==' cannot be applied to two 'Foo' operands". What is the problem and how do I fix it?
推荐答案
Foo没有任何具有任何属性的父类来执行比较,所以它不知道如何比较自己。
Foo has no parent class that has any properties to perform comparison, so it has no idea how to compare itself.
相反,您需要采用Equatable协议,然后告诉您包含 ==
运算符,此时您将定义您的操作:
Instead you need to adopt the Equatable protocol, which will then tell you to include the ==
operator, at which point you would define your action:
您的其他选项是使用===,它将比较引用,因此唯一的方法就是这两个项目都指向同一个实例。
Your other option is to use ===, which will compare the references, so the only way this will pass is both items are pointing to the same instance.
class Foo : Equatable{
var randomeVar:String?
func saySomething(){
print("Something")
}
static func ==(lhs: Foo, rhs: Foo) -> Bool
{
//what makes us equal
}
}
这篇关于如何解决“二元运算符”=='不能应用于两个'Foo'操作数“?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!