Source: Google Search

Using Higher order functions: A practical example in Swift

Higher order functions are described to be pretty advanced in the sense of how it works and why it works. But seriously, who cares, right? Of course as long as you know how to use it. People might argue with me, but I think its more important to know where to use something than how to use it (Hint: IDEs do most of the things right?).

“Oh, Cut the crap! show us some code!”

Sure. I will show you a more practical example of where and how to use it. First accept this is valid.

let var = myFunction() -> Void

We will experiment more about that later. 😉 For now, lets hear a story.

Suppose, in a controller somewhere we have few functions calling network request with a authentication token named token . If the token is expired we don’t want to disturb the user. We try login automatically and try doing what we are doing. Now as we are calling the same tryLogin() function from several different functions, we need to keep track which one should we call back after fetching new authentication token. There are some ways to do it, we can choose any. Here is a demonstration how we can do that the easy way.

See how I used switch to determine which function to call in the tryLogin() function. The problem is that, as the number of calling functions increases that switch gets larger too. Also that tracking gets very massy if you want to modify functions (delete or reorder senderId). 😨

Now, I can show you a better approach where we will remove that dependancy from tryLogin() function. Of course using Higher Order Functions.

Here what I did, passed the function itself as a parameter of tryLogin() function instead of using a sender Id.

The argument parameter tryLogin(callingFunction:) callingFunction itself is the function we sent. So calling it will do the callback we deserve.

Happy now? 😎

Well, if you are not satisfied, i am guessing you are more of a traditional learner. Thats ok. Here is a video tutorial that helped me a lot understanding the concept.

Remember the line of code I said is valid? Hope you will find some connection between the implementation code snippet and the statement. Well we can do some awesome stuff with that (practically 😄). But maybe later.


If you like the article give some claps. If you don’t, please don’t hate me.

Happy Coding… :)