Swift generics with extension — Part 3

Mohit Kumar
2 min readApr 22, 2020

--

Before starting this, I suggest to go through Part 1 and Part 2.

In this article I will keep it very sort and simple with some realtime example. Consider case when you define some Custom generic class, and you want some methods of that class to be accessible for a particular datatype only then extension will be of very use for you.

Let’s take example where you define some Generic type which perform following operations:

  1. Print value
  2. Increment number by 1
  3. Length of strings

So in first case, it will work with Int and String with both, second case will work with numeric values only and third case will work with string value only.

So how you will define a common class to handle these case so that if we using Int in generic type then it should not be able to call length() method and if using String then should not be able to call increment() method.

Let’s look at code below:

In above code I believe I am able to give proper explanation of my theory. In above code you can see that:

  1. Calling printLength will not work for Int type.
  2. Calling increment will not work in String type.
  3. Calling printText will work for all type of generic instances.

In my all 3 article I got conclusion about use of generic that we can really optimise our code up-to a good standard by using Generic. Generic is very powerful tools of any language. Writing high level of software without user of Generics is not possible.

You can find use of generics in our app from my sample code to create a generic tableView (link given below), I have used same tableView for multiple type of Objects and Cell.

Thanks.

--

--