Generics in Swift — Part 1

Mohit Kumar
3 min readApr 22, 2020

--

In this article I will be covering generics in swift and how to use them in our application. Generic a very powerful tool of any language which help you to write optimise code. Before start for this, lets consider example to swap two values:

In above code we are taking 2 Integer and swapping values of them using third variable. So what is problem with above code? Well if you have to swap value of type String OR Float, then with this approach you will require to write different method for each data type which is not a good practise.

So to avoid above issue we can use Generics in our application, Generic allow us to define a generic data type so that any kind of object can be pass to method. So let’s look a Generic version of above example:

So in above code you can see that we have used variable T as placeholder of datatype. Let’s understand the code in pointers:

  1. First we append <T> in function body, which help function to know that that T is some kind of generic datatype and need to be replaced with actual datatype while executing.
  2. Then we defined value1 and value2 as datatype of T. So now this function will receive any kind of object.

Generic type in swift

Swift allow you to define your own generic type, You can define your own custom class, struct, enum which can accept any type of data type. This is same like Array and Dictionary.

In this example we are creating one queue which can accept all kind of data:

In above example we have created one Queue struct. You can use it for any kind of datatype like Int, Float, String etc. You can pass datatype while creating object of struct.

Type Constraints in generics

Sometime we need to add some constraints on our data type. For example if we have to write a method to find element from an array then we will require to traverse whole array and match element to search in the array. In this case we will use operator == to match values. But what if generic type accept some class OR struct object? In this case compiler will give error that error: binary operator ‘==’ cannot be applied to two ‘T’ operands

Example with error case:

Above code will give error as binary operator ‘==’ cannot be applied to two ‘T’ operands Since we don’t know type of T.

To fix this issue we can tell compiler that T confirms to Equatable, Check example below:

In above code we have updated <T> to <T: Equatable>, this help compiler to know that generic type is allowed to use ==. So now if you will pass any object which doesn’t confirm to Equatable, compiler will give error at compile time.

Another good example for above approach is given below where you can define your own protocol and your own generic type:

I hope you enjoyed above article on generics, Now we can move to part 2 of this article where we will be covering Associated type in generics.

Part 2: https://medium.com/@mohitchaudhary_43770/generics-in-swift-part-2-790d6e1237c5

--

--