O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Generic data structures

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required