-
Book Overview & Buying
-
Table Of Contents
Mastering Swift 6 - Seventh Edition
By :
Generics allow us to write very flexible and reusable code that avoids duplication. With a type-safe language, such as Swift, we often need to write functions, classes, and structures that are valid for multiple concrete types. Without generics, we would need to write separate functions for each type we wish to support. With generics, we can write one generic function to provide the functionality for multiple types. Generics allow us to tell a function or type, “I know Swift is a type-safe language, but I do not know the type that will be needed yet. I will give you a placeholder for now and will let you know what type to enforce later.”
In Swift, we can define both generic functions and generic types. Let’s look at generic functions first.