Connect with us


How to Use Generics in Swift

Make your code minimal.

One of our main responsibilities as developers is to keep the code as simple as possible and avoid repeating code. Generics is one of the functionalities which provides lots of benefits like better performance, less code, reusable code, etc. So I believe it is important that every developer have knowledge about Generics.

Why do we need Generics in Swift?

As you can see, SearchUtil class will take a list of Integers as a parameter. searchItem function will take an integer (which needed to be searched) as an input and return the result. This seems fine. isn’t it ?. Then what’s the problem?

Suppose, now you have to search for an item that is a list of strings or objects. What will you do? There are two possible solutions to this problem.

  1. Create another SearchUtil class and searchItem function which will take the strings or object type and return the result.
  2. Use Generics

Solution 1 obviously is not a good idea. Because we have to write lots of code and many codes will be repeated. In this scenario, Generics come to the rescue.

What are Generics?

According to official documentation,

Generics are classes, structures, interfaces, and methods that have placeholders (type parameters) for one or more of the types that they store or use. A generic collection class might use a type parameter as a placeholder for the type of objects that it stores; the type parameters appear as the types of its fields and the parameter types of its methods. A generic method might use its type parameter as the type of its return value or as the type of one of its formal parameters.

In a nutshell,

Generics is a flexible system that allows you to work with any data types. It changes the type burdens from you to compiler .

I think this is the simplest explanation.

Generics in Action

Now we will convert the above example into Generics. To convert SearchUtil class as a Generics we need to modify it like below

class SearchUtil<T: Equatable>

Here T indicates that any kind of type can be used as an argument. I am using Equatable protocols because the object will be checked for equality.

Also, we need to modify searchItem function.

func searchItem(element: T, foundItem: (T?)->())

Now we can use any type we want.

let searchUtil = SearchUtil(list : listOfObjects)
let searchUtil = SearchUtil(list : listOfNumber)

The above code will work without any issue. Let’s see a real example.

Here we have created a Person struct. We are performing a search operation on listOfPerson . Now if you want to perform the search operation on a list of Integers, you can do it without making any change in the SearchUtil or searchItem

let searchUtil = SearchUtil(list: [Int](arrayLiteral: 24,25,26))
searchUtil.searchItem(element: 26) {(result) -> () in
    print(result ?? "Not found")

It is awesome, isn’t it?

Full Article: Farhan Tanvir @ Level Up Coding