[swift-evolution] Polymorphic behavior for overloaded == (and other) operators
Frederick Kellison-Linn
fred.kl at me.com
Fri Dec 11 11:00:12 CST 2015
Hi Chris,
Thanks for the response, I’m glad to hear that. Is this something that is planned/feasible for Swift 3?
FKL
> On Dec 11, 2015, at 1:02 AM, Chris Lattner <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/f276eb6a/attachment.html>
More information about the swift-evolution
mailing list