[swift-evolution] Overriding computed properties with let constants?

Haravikk swift-evolution at haravikk.me
Sat Apr 23 16:06:19 CDT 2016


I don’t think using a let constant should prevent a further sub-class from overriding again, that’s what the final keyword should be for.

It would still need to be implemented like this behind the scenes though:

    override var x:Int { return 7 }

By the same token you could also allow var to implicitly create something like the following:

    private var _x = 7
    override private(set) var x:Int {
        get { return _x }
        set { _x = newValue }
    }

I’m not sure what my preference is though; while being able to do overrides with stored property-like syntax might be convenient and tidy in some cases, it’s probably better to force developers to use explicitly computed properties to be clear what’s really going on to make it actually work.

> On 23 Apr 2016, at 20:30, Adrian Zubarev via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I already see the problem here:
> 
> class A { var x: Int { return 42 } }
> class B: A { override let x = 7 } // assume that will work
> class C: B { override var x: Int { /* wait this wont work anymore */ } }
> 
> You won’t be able to override an immutable constant.
> 
> I don’t like such a change.
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 23. April 2016 bei 21:19:27, Roman Zhikharevich via swift-evolution (swift-evolution at swift.org <mailto:swift-evolution at swift.org>) schrieb:
> 
>> I think, it could be a good idea to make computed properties overridable with let constants.
>> 
>> Something like this:
>> 
>> class Parent {
>>     var x: Int {
>>         let x = 42
>>         /*
>>          * Compute x...
>>          */
>>         return x
>>     }
>> }
>> 
>> class Child: Parent {
>>     /*
>>      * Sometimes you need to override computed properties with simple constants.
>>      * This is currently done like this.
>>      */
>>     //override var x: Int {return 7}
>>     
>>     /*
>>      * But this looks neater.
>>      * Currently this gives "error: cannot override with a stored property 'x'".
>>      */
>>     override let x = 7
>> }
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-evolution <https://lists.swift.org/mailman/listinfo/swift-evolution>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160423/a490deca/attachment.html>


More information about the swift-evolution mailing list