Implementing Equatable for Protocols in Swift

Last week I attended iOSDevCampDC, where I had the pleasure of hearing @ayanonagon‘s talk on testing. You can view the code sample here.

For testing purposes and to my surprise, she implemented a default Equatable on a protocol similar to this:

I say to my surprise, because I never thought of having all objects that conform to a protocol have a default implementation like this. It definitely made me think! And of course it made sense for Ayaka’s example at the time – she added this purely for testing purposes.

But when I played around with this and thought about it some more, I started seeing future bugs. What if the value that conforms to this protocol has other properties as well. Now it has default equality that might not work as intended. For example:

Of course this would be fixed if ColorfulRectangle got it’s own custom Equatable implementation:

But the worry is that this could be easily forgotten, especially since the compiler wouldn’t complain about the equality not being implemented.

So while implementing default Equality on a Protocol level is pretty powerful, it’s also a little dangerous. Use responsibly!

Join me for a Swift Community Celebration 🎉 in New York City on September 1st and 2nd. Use code NATASHATHEROBOT to get $100 off!

Enjoy the article? Join over 14,500+ Swift developers and enthusiasts who get my weekly updates.