Generics in Swift

Swift Generics

Swift Generics allows us to create a single function and class (or any other types) that can be used with different data types.

This helps us to reuse our code.

Generic Function

In Swift, we can create a function that can be used with any type of data. Such a function is known as a Generic Function.

Here's how we can create a generic function in Swift:

image

Here,

  • We have created a generic function named displayData().

  • T used inside the angle bracket <> is called the type parameter .

And based on the type of the value passed to the function, the T is replaced by that data type (Int, String, and so on).

Example

Generic Class

Similar to the generic function, we can also create a class that can be used with any type of data. Such a class is known as Generic Class.

Example

In the above example, we have created a generic class named Information. This class can be used to work with any type of data.
We have created two objects of Information

  • var intObj = Information<Int>(data: 6)
    • the type parameter T is replaced by Int. Now, the Information works with integer data.
  • var strObj = Information<String>(data: "Swift")
    • the type parameter T is replaced by String. Now, the Information works with string data.

Note: Similar with Struct

Type Constraints in Generics

In general, the type parameter can accept any data type (Int, String, Double, …).

However, if we want to use generics for some specific types (such as accepting data of number types) only, then we can use type constraints.

Here's how we create type constraints:

  • <T: Numeric> adds constraints to the type parameter. It defines that T needs to conform to the Numeric protocol.

Example
image
image

  • If we try to pass other types, say String, we'll get an error: argument type String does not conform to the expected type Numeric

Advantages of Swift Generics

1. Code Reusability

With the help of generics in Swift, we can write code that will work with different types of data. For example,

func genericFunction<T>(data: T) {...}

Here, we have created a generics function. This same function can be used to perform operations on integer data, string data, and so on.

2. Used with Collections

Swift array uses the concept of generics. For example,

// creating a integer type array

var list1: Array<Int> = []

// creating a string type array

var list2: Array<String> = []

Here, list1 array that holds Int values and list2 array that holds String values.

Similar to arrays, dictionaries are also generic in Swift.