Generics in Swift 4.2 (iOS)

Generics is one of the most powerful feature of Swift. It enables developers to write reusable, and flexible functions.

Infact Swift Library is built in generic code. For ex: Swift Array and Dictionary are generic collections. We can create array of Int values, array of String values, or array of any type.

Why Generics?

Enough of definition, Let’s understand it by understanding a very common problem in software development(Duplicate Code). Suppose you want to write swap function for Int type. It’s simple using inout params.

func swapTwoInts(_ a: inout Int, _ b: inout Int) {

  1. let temporaryA = a
  2. a = b
  3. b = temporaryA}

But 5 days later, data changes and now you want to swap double.

What will you do?

Yeah right!!! You can right like below

func swapTwoDoubles(_ a: inout Double, _ b: inout Double) {….}

But 10 days later, now you want to swap String.

This is irritating now…

I don’t want to write another function and another function and another function…….This is bad programming and can lead to Bugs and maintenance headaches.

This is where Generics save us. Let’s write Single function which we don’t have to change untill the end of time.

func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
  1. let temporaryA = a
  2. a = b
  3. b = temporaryA
  4. }

If you compare with previous versions, you will notice <T> and T has been introduce. The generic version of the function uses a placeholder type name (called T, in this case) instead of an actual type name (such as Int, String, or Double). The placeholder type name doesn’t say anything about what T must be, but it does say that both a and b must be of the same type T, whatever T represents. The actual type to use in place of T is determined each time the swapTwoValues(_:_:) function is called.

Note: The brackets tell Swift that T is a placeholder type name within the swapTwoValues(_:_:) function definition. Because T is a placeholder, Swift doesn’t look for an actual type called T.

The type to use for Tis inferred from the types of values passed to the function.

You can provide more than one type parameter by writing multiple type parameter names within the angle brackets, separated by commas.