Generic type in Swift

Nitesh Kumar Pal
Globant
Published in
4 min readMar 13, 2020
If you are also thinking same let’s demystify the usage of generic type.

Generic code gives the power to make your code flexible and reusable that can work with any type. It avoids duplications and expression in an abstract way.

Following are the topics which we are going to cover in this tutorial:

  • Generic Function
  • Generic Class, structure
  • Generic Enum
  • Generic with constraints
  • Protocol as associated type
  • where clause for associated type

Generic Function:

A function which shows polymorphism for all the types.

  • You can define generic function by providing a type placeholder inside angular brackets <T>.
  • You can use anything instead of T for example: Type, DataType etc. whatever you want. e.g. func printArray<Type>(collection: [Type])

Have a look at the note given in apple documentation👇

NOTE:
Always give type parameters upper camel case names (such as T and MyTypeParameter) to indicate that they’re a placeholder for a type, not a value.

  • You can use type T to indicate the type of parameter which is going to pass in the method while calling this method.
  • printArray method identifies types due to type inference for array of int and array of string.

You can declare multiple generic types which can be different while calling like the following:

Generic Class, structure:

Generic Class or Structure can be defined with generic type that can be a type of property.

For Example:
You can Define Generic Company by adding generic type after struct or class name enclosed in angular brackets as <Industry>.

Generic Enum

Just like struct or class enum can be defined as generic. Please check the example below how Model generic type is associated with response case

In the above example, you can see the power of generic code where one codebase as ServerResponseType enum is working for all the Model types that are passed as the associated value of .response case as defined.

Generic with constraints:

We can add constraints to Generic type wherever we define it in function, class, structure or enum.

Below 👇 is the syntax for declaring generic placeholder with constraint:

Generic Placeholder : Constraint // Constraint can be any class or Protocol

E.g. T : Hashable

This declaration means, Generic type parameter inherits from a specific class or conforms to a protocol or protocol composition.

Example of protocol compositions are the following:

  1. Hashable & Comparable,
  2. FileHandlingProtocol: FileReadProtocol, FileWriteProtocol

So we can use these compositions like follow:

T: Hashable & Comparable

T: FileHandlingProtocol

Let's look at the below example 1 we are adding constraints such that Company can associate with such Industry type that must confirm IndustryIdentity protocol.

Example 1:

Example 2:

In the below example we are adding a constraint to server response such that it must have id.

Note: Identifiable is predefined protocol in swift, here it’s taken for example purpose only to have a clear understanding.

Since Service is not confirming Identifiable protocol so at the time of passing it as value to ServerResponseType.response it will prompt compile-time error like below:

Compile time error: Generic enum ‘ServerResponseType’ requires that ‘Service’ conform to ‘Identifiable’

Protocol as associated type

We cannot define generic type placeholder directly in Protocols as we declare in function, class, structure or enum. There is another way to define Generic type as placeholder with protocol that is associated type.

Syntax:

Here GenericPlaceholder can be anything whatever we like indicating it as Generic type. And GenericPlaceholder can be used as parameter type in any method, property or subscript declaration in the protocol.

GenericPlaceholder can be added with constraints as well.

e.g. associatedtype GenericPlaceholder: Comparable

In the below example protocol Identifiable declare var id with generic type IDType, where id will be of type IDType.

It can be confirmed either way as below:

In the first code snippet compiler automatically identifies the type of id due to type inference and considers IDType as Int for the Struct Product.

and in the second snippet it’s more for the readability purpose and to instruct the compiler to deal with this type for its associated methods, properties, subscripts, etc. You can test it with the autocorrection feature of compiler.

Where clause for associated type

For adding more requirement on associatedtype we can use where clause. its syntax is

Let’s check the example:
Let’s assume there is a requirement for having different warehouses in different cities, each can contain a certain type of product and each warehouse knows all the branches of this particular product. so let’s find the solution to this problem with help of generic.

Where to go from here:

If you are more inquisitive to check the following advance usage of Generic which I have not covered in this tutorial. You can learn them through apple’s well-documented site for Swift programming LanguageGuide.

--

--