O'Reilly logo

Swift Quick Syntax Reference by Matthew Campbell

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

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 ...

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