spacitron spacitron - 1 month ago 10
Swift Question

How to resolve "Binary operator '==' cannot be applied to two 'Foo' operands"?

I created a class Foo as follows:

class Foo{

var randomeVar:String?

func saySomething(){
print("Something")
}
}


I now want to compare different instances of foo as follows:

let foo1 = Foo()
let foo2 = Foo()
if foo1 == foo2{
print("Cool")
}


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?

Answer

Foo has no parent class, so it has no idea how to compare itself.

Instead you need to assign it 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")
    }

    func ==(lhs: Self, rhs: Self) -> Bool
    {
      //what makes us equal
    }
}
Comments