Search code examples
iosswiftpolymorphismprotocols

Protocols versus polymorphism in swift


I am rather new to object-oriented programming and I am attempting to wrap my head around protocols, delegates, and polymorphism. I recently watched a training video that promoted that when you have two classes that are similar with similar method implementations, a protocol is the best solution for achieving this elegantly. That makes sense. However, some additional research has led me to discover polymorphism and it sounds like that is also a preferred approach, whereas you could simply use the base class to model the functionality and update these methods in the subclasses.

So, I have two questions. First, is my understanding of polymorphism correct? I am still rather new to all of these concepts. Second, do protocols trump polymorphism and when would you use one over the other?

Thanks!


Solution

  • There are cases in which protocols are more appropriate way to go, and cases in which a base class is the solution.

    In Swift base class allows you to share the same implementation thus reducing code redundancy. However, a base class does not force its subclasses to override its methods. So if all the subclasses are supposed to override some specific method, base class will be short to enforce it (there are no abstract classes in swift that would enable mixing implementation with requirements). There are ways how to "hack" it, e.g., by including fatalError() in base class implementation to enforce the programmer to override it (otherwise the base implementation would cause crash) - but that is a runtime error. So if the base class is just for you, it can be a good approach, but if you are implementing a library/framework and you expect the user of the library to subclass it, then you have to consider these concerns.

    Protocols on the other hand are contract definitions. Protocol defines which methods have to be implemented in order to implement that protocol. So each protocol implementing class will be forced to implement those methods. This is usually something you want - you want to bind the implementing class by the contract to fulfil the requirements of the protocol. However, making the implementing classes to share the code is a bit harder. Take a look into protocol extension for this. Protocol extensions allow you to add "default" implementation to the protocol methods.

    You can take a look at my blog article about protocol oriented programming for some more polemics about it.