December 2015
Intermediate to advanced
400 pages
13h 3m
English
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(_:f:) 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 ...
Read now
Unlock full access