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 a generic function. This T
placeholder can then be used anywhere within the type instead of a concrete type definition.
To create an instance of this type, we would need to define the type of items that our list will hold. The following examples...