[swift-evolution] Polymorphic behavior for overloaded == (and other) operators

Chris Lattner clattner at apple.com
Fri Dec 11 13:26:55 CST 2015


> On Dec 11, 2015, at 9:00 AM, Frederick Kellison-Linn <fred.kl at me.com> wrote:
> 
> Hi Chris,
> 
> Thanks for the response, I’m glad to hear that. Is this something that is planned/feasible for Swift 3?

It’s desired, but not considered critical for Swift 3, so it will depend on how times work out.  If ABI stability ends up taking more time than expected, it will probably get pushed out.

-Chris

> 
> FKL
> 
>> On Dec 11, 2015, at 1:02 AM, Chris Lattner <clattner at apple.com <mailto:clattner at apple.com>> wrote:
>> 
>> On Dec 8, 2015, at 10:32 PM, Frederick Kellison-Linn via swift-evolution <swift-evolution at swift.org <mailto: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/20151211/b2bda330/attachment.html>


More information about the swift-evolution mailing list