O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

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

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

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