Generic types

A generic type is a class, structure, or enumeration that can work with any type, just like Swift arrays and optionals can work with any type. When we create an instance of our generic type, we specify the type that the instance will work with. Once a type is defined, it cannot be changed for that instance.

To demonstrate how to create a generic type, let's create a simple List class. This class will use a Swift array as the backend storage and will let us add items or retrieve values from the list.

Let's begin by seeing how to define our generic List type:

struct List<T> { 
} 

The preceding code defines the generic List type. We can see that we use the <T> tag to define a generic placeholder, just like we did when we defined ...

Get Swift 4 Protocol-Oriented Programming - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.