-
Book Overview & Buying
-
Table Of Contents
Mastering Swift 6 - Seventh Edition
By :
A generic type is a class, structure, or enumeration that can work with any type, just like the way Swift arrays and dictionaries work.
Swift arrays and dictionaries are written so that they can contain any type. The catch is that we cannot mix and match different types within an array or dictionary.
When we create an instance of our generic type, we define the type that the instance will work with. After we define that type, we cannot change the type 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 have the functionality to add items to the list or retrieve values from the list.
Let’s begin by seeing how to define our generic List type:
class List<T> {
}
We can see that we use the <T> tag to define a generic placeholder, as we did when we defined a generic function. This T placeholder can then...