Swift Generics

Ramesh Chavan
2 min readOct 4, 2022

--

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

Swift Generic Function

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:

// create a generic function
func displayData<T>(data: T){
...
}

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).

Note: We can provide any name to the type parameter: <S>, <Element>, etc. But generally, we use T.

Example:

// create a generic function
func displayData<T>(data: T) {
print("Generic Function:")
print("Data Passed:", data)
}

// generic function working with String
displayData(data: "Swift")

// generic function working with Int
displayData(data: 5)

Output

Generic Function:
Data Passed: Swift
Generic Function:
Data Passed: 5

Swift 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.

// create a generic class
class Information<T> {

// property of T type
var data: T

init (data: T) {
self.data = data
}

// method that return T type variable
func getData() -> T {
return self.data
}
}

// initialize generic class with Int data
var intObj = Information<Int>(data: 6)
print("Generic Class returns:", intObj.getData())

// initialize generic class with String data
var strObj = Information<String>(data: "Swift")
print("Generic Class returns:", strObj.getData())

Output

Generic Class returns: 6
Generic Class returns: Swift

Type Constraints in Swift 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:

func addition<T: Numeric>(num1: T, num2: T) {
...
}

Note: Numeric is the built-in protocol for numeric values like Int and Double.

Advantages of Swift Generics

1. Code Reusability

2. Used with Collections

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ramesh Chavan
Ramesh Chavan

Written by Ramesh Chavan

Like to work on iOS, Android, UIPath and Graph DB

No responses yet

Write a response