How to use Generics in Swift?

You may confuse or in fear of to use of Generics in Swift. Today we will see, How to use Generics in Swift. Swift Generics allow you to write generic code. Generic code allows us to write reusable code and also we can avoid redundancy of code throughout the project, generic programming allows us to write code once and very clean and in abstracted manners. if you think writing generic code sounds very complicated in terms of implementation. you have wrong assumptions. generics are a compelling feature in swift.

By using generics in code we can reusable code and Generic code avoid redundancy of code.

Generics In Swift programming language.

I would like to tell you, you are already using generics in your code, don’t worry I will tell you, how?, If you have used “Array” earlier, you are using generics. I have been waiting a long time to making this tutorial about generics.

The array is nothing but a collection of data, We are appending and deleting data from Array, Data could be anything, it may be int, String, or Any business model object. The Array itself is a generic struct, Element is nothing but generics in swift.

How to use generics in code:

here I have written a simple code for finding integer element from Array. In this function, I am sending an array with integer value element suppose to find.

Suppose I have one more String array like :

I want to find Akash is present in string Array.

Ohh, I got this compiler error. “Cannot convert value of type ‘[String]’ to expected argument type ‘[Int]'”

I got type casting error, I am passing String Array Instead of Integer Array to function. This function is written only for functioning with integer array, For manipulating String array and find an element from String array we have to write the same function with a different type parameter like :

Do you think this idea will work?. Yes, but writing the same function twice for the sake of resolve compiler error or working. I think it’s going wrong somewhere. Here you can see code redundancy is occurring.

Don’t worry I will show you how to write a generic function for any data type as an input. Here <T> is nothing but generic type, T could be Integer, Float, String, Array of objects. The Comparable protocol is optional, I used a Comparable protocol for comparing generic type objects. you can directly write <T> instead of <T: Comparable>.

Generic Type Parameters

Now, this is how you can manipulate both array:

Conclusion:

Writing generic code is very standardised coding way for the sake of code reusability and avoid code redundancy. you can use generic type in Model class, Controller and anywhere you want. Keep Coding

Leave a Comment