O'Reilly logo

Learning Swift by Andrew J Wagner

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

Defining a generic

A generic is very similar to a type alias. The difference is that the exact type of a generic is determined by the context in which it is used, instead of the implementing types. This also means that a generic only has a single implementation that must support all of the possible types. Let's start by defining a generic function.

The generic function

In Chapter 5, A Modern Paradigm – Closures and Functional Programming, we created a function that helped us find the first number in an array of numbers that passes a test:

func firstInNumbers(
    numbers: [Int],
    passingTest: (number: Int) -> Bool
    ) -> Int?
{
    for number in numbers {
        if passingTest(number: number) {
            return number
        }
    }
    return nil
}

This would be great if we only ever deal ...

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