Chapter    48

Generics

When you are working with types such as Int or String in Swift, you typically must declare the type or have the type inferred from the value. While this pattern makes some code clearer, sometimes you want to be able to use any type in your code. Generics gives you a way of doing just this.

To use generics, you must add <T> after a function name. Then you can substitute T in place of the type name. For example, let’s say you are working with your Person and Employee classes from Chapter 40. Maybe you decide that you want to add a function to print information about the types of instance that you could have. Listing 48-1 shows how you can use generics to create one function for both types of instances.

Listing 48-1. Using ...

Get Swift Quick Syntax Reference 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.