[swift-evolution] Method dispatching issue with subclasses implementing Equatable protocol.

Francisco Javier Fernández Toro fran at gokarumi.com
Wed Jan 18 10:52:49 CST 2017


Thank you for your answer Joe,

you are right the equal(to:) wasn't a valid override, but even after using
the one you've proposed, the behavior is not the expected one


let a = Subclass(foo: 1, bar: 1)
let b = Subclass(foo: 1, bar: 2)

(a == b) != (a != b) // Prints true

let x = SubclassWithDifferentOperator(foo: 1, bar: 1)
let y = SubclassWithDifferentOperator(foo: 1, bar: 2)

(x == y) != (x != y) // Prints false

As you can see above if a subclass does not implement the global function !=,
the equal operation seems to be broken.

---

Fran Fernandez

On Wed, Jan 18, 2017 at 5:44 PM, Joe Groff <jgroff at apple.com> wrote:

>
> > On Jan 18, 2017, at 2:59 AM, Francisco Javier Fernández Toro via
> swift-evolution <swift-evolution at swift.org> wrote:
> >
> > Hi,
> >
> > I've found that when you have a class hierarchy which implements
> Equatable, if you want to have the != operator working as expected, you
> need to override it, it's not enough with ==.
> >
> > If you don't define you own subclass != operator, Swift compiler will
> use the super class to resolve that operation.
> >
> > Is there any reason for that?
>
> The `equal(to:)` method inside `Subclass` is not a valid override of
> `Superclass` because its argument only accepts `Subclass` instances, but
> the parent method needs to work with all `Superclass` instances. If you
> write it as an override, it should work:
>
> class Subclass: Superclass {
>     let bar: Int
>     init(foo: Int, bar: Int) {
>         self.bar = bar
>         super.init(foo: foo)
>     }
>
>     override func equal(to: Superclass) -> Bool {
>       if let toSub = to as? Subclass {
>         return bar == toSub.bar && super.equal(to: to)
>       }
>       return false
>     }
> }
>
> We should probably raise an error, or at least a warning, instead of
> silently accepting your code as an overload. Would you be able to file a
> bug on bugs.swift.org about that?
>
> -Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170118/58fc14f9/attachment.html>


More information about the swift-evolution mailing list