[swift-evolution] Polymorphic behavior for overloaded == (and other) operators
Chris Lattner
clattner at apple.com
Fri Dec 11 00:02:20 CST 2015
On Dec 8, 2015, at 10:32 PM, Frederick Kellison-Linn via swift-evolution <swift-evolution at swift.org> wrote:
>
> Currently, implementing an ā==ā function for a custom class can be somewhat cumbersome. In the simple hierarchy:
>
> class A {
> var a: Int
> init(_ a: Int) {
> self.a = a
> }
> }
>
> class B : A {
> var b: Int
> init(_ b: Int, _ a: Int) {
> self.b = b
> super.init(a)
> }
> }
>
> A reasonable implementation of == would seem to be
>
> func ==(lhs: A, rhs: A) -> Bool {
> return lhs.a == rhs.a
> }
>
> func ==(lhs: B, rhs: B) -> Bool {
> return lhs.a == rhs.a &&
> lhs.b == rhs.b
> }
>
> Iād be interested to know if there is any interest taken in this problem and whether possible solutions have been discussed. If == were instead behaved as if it were a method of its first argument (as in a .equals(other) method) then the solution above is sufficient to avoid returning the wrong result, but being forced to use .dynamicType for something as basic as equality checking seems cumbersome to me.
Hi Frederick,
The preferred approach is to allow operators to be defined inside of types. This would allow them to be dynamically dispatched inside of classes.
-Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151210/915f3370/attachment.html>
More information about the swift-evolution
mailing list