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 ...

Get Mastering Swift 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.