When not to use generics
One of the things that we should watch out for while using generics is to avoid using them when we should be using protocols. This is, in my opinion, one of the most common misuses of generics in other languages. Let's take a look at an example so that we know what to avoid.
Let's say that we define a protocol called WidgetProtocol
, which is as follows:
protocol WidgetProtocol { //Code }
Now, let's say that we want to create a custom type (or function) that will use various implementations of the WidgetProtocol
protocol. I have seen a couple of instances where developers have used generics with a type constraint to create custom types as follows:
class MyClass<T: WidgetProtocol> { var myProp: T? func myFunc(myVar: T) { //Code } }
While this is a perfectly valid use of generics, it is recommended that we avoid implementations like this. It is a lot cleaner and easier to read if we use WidgetProtocol
without generics...