Member-only story
Create Generic Protocols With Associated Types in Swift
How to make protocols generic and the advantages of doing so

While discussing generics in Swift, we learned how to make structs, enums, and classes generic.
We discovered how to pass in abstracted type information at the compile time, leaving it up to the compiler to carry that information from compile time to run time. We used protocols to declare the capability of those types.
But what about protocols? How do we make protocols generic and what are the advantages of doing so?
In this article, we will discuss generic protocols or associated types.
Defining a Generic Protocol
Protocols might come across to you as something that is already generic as any type can conform to a protocol, but what about the internals of the protocol?
Can we come up with a protocol where the internals of the protocol are generic?
The short answer to this question is that it is possible, but implementation is a bit different from what we discussed for other generic types. The first step is to define an interface using a protocol, as shown in the following code:
protocol Stack {}
By definition, a Stack
is just an array with limited functionality. In general, a Stack
can perform the following functions to the elements it holds:
Push
an element to the top of theStack
.Pop
to remove the top element.Peek
at the top element without removing it from theStack
.
Stack
is usually used when we want to maintain a LIFO (Last In First Out) order, i.e. we get the last element pushed to the Stack
when popping from the Stack
.
Now that we understand the functions, let’s define the interface in code: