Member-only story
How to Achieve Dynamic Dispatch Using Generic Protocols in Swift 5.7
It’s never been easier!

Dynamic dispatch is one of the most important mechanisms in Object-Oriented Programming (OOP). It is the core mechanism that makes run-time polymorphism possible, enabling developers to write code that decides their execution path during run-time rather than compile-time.
As easy as it seems to achieve dynamic dispatch in OOP, it is not the case when it comes to Protocol-Oriented Programming (POP). Trying to accomplish dynamic dispatch using protocols always comes with unpredicted difficulties due to various limitations in the Swift compiler.
With the release of Swift 5.7, all these have become history! Achieving dynamic dispatch in the realm of POP has never been easier. In this article, let’s explore what kind of improvements we get from Swift 5.7 and what it takes to accomplish dynamic dispatch using protocol with associated types.
So without further ado, let’s get right into it!
Note:
If you’re unfamiliar with the
some
andany
keyword in Swift, I highly encourage you to first read my blog post called “Understanding the “some” and “any” keywords in Swift 5.7“.
First Things First
Before I can start showing you the improvements in Swift 5.7, let’s define the protocols and structs that we need for our sample code throughout this article.
The definitions we have above are similar to what we are using in my previous article, but with a little bit of a twist. Here in our Vehicle
protocol, we have 2 function requirements, startEngin()
and fillGasTank(with:)
. For the sake of demonstration, We will try to achieve dynamic dispatch using these 2 functions in both Car
and Bus
structs.