O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

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

Generic Functions and Methods

Remember the map(_:) method defined on Array from Chapter 13? map(_:) applies a closure to each element in the array and returns an array of the results. Given what you just learned about generics, you can now implement a version of this function yourself. Add the following code to your playground.

Listing 22.6 Your own map function

...
func myMap<T,U>(_ items: [T], _ f: (T) -> (U)) -> [U] {
    var result = [U]()
    for item in items {
        result.append(f(item))
    }
    return result
}

The declaration of myMap(_:_:) may look pretty ugly if you have not been exposed to generics in other languages. Instead of the concrete types you are familiar with, it just has T and U, and there are more symbol and punctuation ...

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