[swift-evolution] [Pitch] Requiring proactive overrides for default protocol implementations.

Erica Sadun erica at ericasadun.com
Thu Apr 28 21:53:29 CDT 2016


> On Apr 28, 2016, at 8:46 PM, Xiaodi Wu <xiaodi.wu at gmail.com> wrote:
> Let's return to the toy example. Suppose I license the following code from a third party. I am allowed to incorporate it unmodified into my project:
> 
> ```
> // I cannot touch any of the following code
> struct A {
>     func frobnicate() { print("A") }
> }
> struct B {
>     func frobnicate() { print("B") }
> }
> struct C { }
> ```
> 
> The code above has three types that conform to no protocols. Nothing would change on adoption of your proposal. As licensed to me from the third party, there are no protocols for it to conform to.
> 
> Now, in a separate file, as part of my own code, I want to conform these three types to a protocol of my own design, Frobnicatable, and supply a default `frobnicate()`:
> 
> ```
> protocol Frobnicatable {
>     func frobnicate()
> }
> extension Frobnicatable {
>     func frobnicate() { print("Default") }
> }
> extension A: Frobnicatable { }
> extension B: Frobnicatable { }
> extension C: Frobnicatable { }
> 
> let a = A()
> a.frobnicate() // "A"
> let c = C()
> c.frobnicate() // "Default"
> ```
> 
> It seems like there is nothing I can do to make this work upon implementation of your proposal.

Is this your desired behavior or is this the behavior you expect?
By implementing a default, you inherit that behavior in all three, because *you* added it.
I expect the compiler to complain at your default because you did not mark it as required.

If you want to use the inherent frobnicate and not the default one that you just added,
you will need to do something like:

extension A: Frobnicate {
   override required frobnicate = A.frobnicate
}

-- E

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160428/31ee6cae/attachment.html>


More information about the swift-evolution mailing list