What are Generics and what kind of problems do they solve?

Swift is a type-safe language. Whenever we work with types, we need to specify them. For instance, a function can have specific parameters and return types. We cannot pass any types but the ones that are specified. What if we need a function that can handle more than one type?

We already know that Swift provides Any and AnyObject, but it is not good practice to use them unless we have to. Using Any and AnyObject will make our code fragile as we will not be able to catch type mismatching during compile time. Generics are the solution to our problem. Let's examine an example first. The following function simply swaps two values (a and b). The values a and b are of the Int type. We should ...

Get Swift Functional Programming - Second Edition 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.