In addition to Generic functions, Swift empowers us to define our own Generic types and data structures. In Chapter 4, Enumerations and Pattern Matching, we developed a simple tree with enumeration. Let's make it Generic so that it can take different types as its leaf
and node
:
enum GenericTree <T> { case empty case leaf(T) indirect case node(GenericTree, GenericTree) } print(GenericTree.node(GenericTree.leaf("First"), GenericTree.node(GenericTree.leaf("Second"), GenericTree.leaf("Third")))) // prints node(GenericTree<Swift.String>.leaf("First"), GenericTree<Swift.String>.node(GenericTree<Swift.String>.leaf("Second"), GenericTree<Swift.String>.leaf("Third")))
With Generics, our tree, which could accept only Int
as a leaf
, became a Generic tree that can accept any type.
Using Generics, it is possible to develop simple and Generic types or data structures such as graphs, linked lists, stacks, and queues.
Let's examine a...