Generics in Swift

Mukesh Shakya
2 min readMay 10, 2020

Apple doc says: Generic code enables you to write flexible, reusable functions and types that can work with any type. You can write code that avoids duplication by using generics in most cases.

Array types belong to generic collections. You can create an array with any data type you like and that’s the real power of generic.

Let see the use of generic. One of the most repetitive code can be contained in network classes where we call our API. We can minimize the repetition of the code in network class using generic.

I will be using the free GET API which gives us the list of countries. The url of the GET API that we are using is https://restcountries.eu/rest/v2/all. The API gives us an array of countries with different information related to countries but for this tutorial we will be only using the country name and its capital attributes.

How do we normally get data from a network call?

In the code above we made a network call using URLSession. Then we created a Codable class for our json data and mapped the name and capital property. Then we decoded the data we got from the network call as an array of our Country object using JSONDecoder.

Now imagine we have to call another GET API which returns an array of information related to languages which exists in the world. Now what we have to do is again write a network call similar to the above one changing the url and data type of decoded object.

We can use a single network call function which can be used for all the GET apis using generics. That’s the real power of generics. Let me show you how.

In the code above we made a network call again using URLSession and Codable again but this time we made a function with an url argument since each network call will be done using a unique url and a completion handler which gives us an optional data object. T is used to denote generic data type in the function and T is type restricted to Codable which means T should be of type Decodable.

What to do if we have to call another get API?

Just create the Codable class with the properties you want in your object and call the same function.

class Language: Codable {
var title: String?
var country: String?
}

fetchData(url: “your url here”) { (languages: [Language]?) in
languages?.forEach({print(“Language name: \($0.title ?? “”), Country origin: \($0.country ?? “”)”)})
}

--

--