9. Becoming Flexible with Generics

Generics are an awesome feature of Swift that allow you to accept more generic types when creating methods, parameters, properties of classes, and so on. Generics allow you to abstract away functionality that would have been repetitious to write. Sometimes you want to write a function that takes not just Ints, but Ints as well as Strings and anything Printable. Without generics, you would have had to write a method multiple times for each type. With generics, you can now write one method for all acceptable types. They’re called generics because you are creating generic versions of a method. The exact type that you accept has not been decided yet. When you write generics, you are removing duplication while showing ...

Get Learning Swift™ Programming 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.