1. 程式人生 > >Swift protocol extension method dispatch

Swift protocol extension method dispatch

Swift protocol extension method dispatch

Protocol extension is one of the coolest features introduced in swift 2.0. They enable new ways to share implementation details between different types, wether they are structs, enums or classes.

Alexandros Salazar has a very nice write up about one tricky cause of issues that could face swift developers in the future. (please read his great

article for more details)

In this article, he expects the following question to be asked:

“Why does the method that I wrote overriding protocol extension X never get called?”

As part of the linked article, he tries to explain the nitty gritty details about how this question is important, and how to reason about method dispatching when using protocol extensions.

The answer to the question can be summarised as following:

IF the inferred type of a variable is the 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 inferred type of the variable is the type — THEN the type’s implementation is called.

If you are like me and you prefer reading decisions from a flow chart, the above reasoning can summarised in the following flow chart: