Custom Higher order functions : MAP

Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner. (ref: Apple Documentation)

Generic functions are more about defining rules rather then a specific implementation. In this article I am going to talk about one of the higher order functions to start with and see how generics helps us build one from scratch.

So let’s start building your very own version of map function and try to understand how generics enable you as a developer to scale that knowledge to build more such custom defined functions right inside your code 😉

Map Function

Swift Library: Map Function Declaration

As we already know the parameter list for the map function, lets try to create custom implementation for our custom map function.

Let’s call this function mapValues and since we want this function to work with Arrays lets declare this function inside an Array extension as follows:

Step 1 : Custom map Declaration

Step 1: As we can see here the map function is generic over a type T. It takes a transformation function as an argument

“Written as transform in the params with specified param values”

Array type in itself is a generic type over a type “Element” and T is the return type of the transformation function. Since the map function returns an array, [T] represents the values to be returned.

Step 2 : Apply transform to each element inside Array

Step 2 : Since we basically want to generate a new array with each element of the input array transforming according to some basic set of rules, we create a new array and the set of rules we want to apply to each element are bundled inside the transform function.

Step 3 : Apply transform to each element inside array

Step 3 : Very simple, apply transform function to each value inside the array and we are done 🙂

You can define your custom functions and pass it to your very own mapValues function and “map your array values” according to your other function but make sure the signature of your function matches the signature or param transform!

Food for thought : Since you can now iterate over the array using mapValues, why should you use a for loop ? should you just abandon the for loop?

Thanks for reading, please share it if you found it useful 🙂

Next I will write about Associated types in Generics, stay tuned!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s