[swift-evolution] Calling default implementation of protocols

Gwendal Roué gwendal.roue at gmail.com
Tue Dec 8 13:42:20 CST 2015


I totally agree.

Yes this limitation only applies to methods declared in the protocol, that are always dynamically dispatched.

For functions that are only declared in the protocol extension, but not in the protocol itself, you can use the static dispatch:

    protocol P {
        func dyn()
    }

    extension P {
        func dyn() {
            print("P.dyn")
        }
        func ext() {
            print("P.ext")
        }
    }

    struct C : P {
        func dyn() {
            // No way to call P.dyn because of dynamic dispatch
            print("C.dyn")
        }
        func ext() {
            (self as P).ext()
            print("C.ext")
        }
    }

    C().ext() // prints P.Ext, C.ext

Gwendal Roué




> Le 8 déc. 2015 à 18:43, Mateusz Zajac via swift-evolution <swift-evolution at swift.org> a écrit :
> 
> If you define a simple protocol like:
> protocol Foo {
>     func testPrint()
> }
> And than you provide a default implementation for testPrint() method in protocol extensions like:
> extension Foo {
>     func testPrint() {
>         print("Protocol extension call")
>     }
> }
> You aren't allowed to call the fault implementation from the structure eg.
> struct Bar: Foo {
>     func testPrint() {
>         self.testPrint()
>         print("Call from struct")
>     }
> }
> This is some sort of limitation as often happens that a default implementation is providing a major part of implementation and only one, simple line is changed in actual struct implementation. If you're using classes you can achieve this by creating a base class and calling a method on super. If you consider structs, there's no such possibility and you always have to write a whole implementation from scratch in each structure which conforms to the protocol.
> You can use composition by creating nested structure, but it's neither logical nor clean... It's rather a hack...
> struct Bar: Foo {
>     func testPrint() {
>         // Calling default implementation
>         struct Dummy : Foo {}
>         let dummy = Dummy()
>         dummy.testPrint()
>         print("Call from struct")
>     }
> }
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151208/d0908360/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: open.gif
Type: image/gif
Size: 43 bytes
Desc: not available
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151208/d0908360/attachment.gif>


More information about the swift-evolution mailing list