[swift-evolution] Proposal SE-0009 Reconsideration

Goffredo Marocchi panajev at gmail.com
Thu May 19 12:12:45 CDT 2016


Hello Jeremy,

It seems it is a little bit more complex than this:
http://allblue.me/swift/2016/01/23/swift-method-dispatch-with-protocol-extension-protocol-extension-and-subclass/
[image: diagram]

   - IF the inferred type of a variable is the protocol:
      - IF the method is in a class conform directly to the original
      protocol:
         - AND the method is defined in the original protocol
            - THEN the runtime type’s implementation is called,
            irrespective of whether there is a default implementation
in the extension.
         - AND the method is not defined in the original protocol,
            - THEN the default implementation is called.
         - ELSE IF the method is in a subclass of another class who conform
      to the original protocol
         - THEN the default implementation of protocol is called.
      - ELSE IF the inferred type of the variable is the type
      - THEN the type’s implementation is called.



On Thu, May 19, 2016 at 5:24 PM, Jeremy Pereira via swift-evolution <
swift-evolution at swift.org> wrote:

>
> > On 19 May 2016, at 13:30, Krystof Vasa via swift-evolution <
> swift-evolution at swift.org> wrote:
> >
> > See this example that demonstrates how it's pretty much unusable (IMHO),
> since whenever you refer to the instance as to the protocol, the default
> implementation gets invoked:
> >
> > protocol MyProtocol { }
> >
> > extension MyProtocol {
> >       func getInt() -> Int {
> >               return 0
> >       }
> > }
> >
> > class MyClass: MyProtocol {
> >       func getInt() -> Int {
> >               return 1
> >       }
> > }
> >
> >
> > let instance = MyClass()
> > instance.getInt() // 1
> >
> > var anyInstance: MyProtocol = instance
> > anyInstance.getInt() // 0 !!!!!!!
> >
> >
> > Since anyInstance is of MyProtocol type, you get the default
> implementation (no dynamic dispatch).
>
>
> That’s because the only information that the compiler has about
> anyInstance is that it conforms to MyProtocol which has no methods so it
> doesn’t know that it can dispatch getInt() to the implementation in
> MyClass. Change the protocol to
>
> protocol MyProtocol {
>     func getInt() -> Int
> }
>
> and it will work as expected.
>
> _______________________________________________
> 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/20160519/08e091fd/attachment.html>


More information about the swift-evolution mailing list