Swift Higher Order functions

In this tutorial you will learn about the Swift Higher Order functions and its application with practical example.

Swift Higher Order functions

In Swift, higher order function is simply a function that either takes a function as an argument, or returns a function. In swift array type has some important higher order functions.

Table Of Contents

Map –

It loop over the elements in a collection and applies the same operation to each of the element in collection. It returns an array containing result after applying required operation on collection elements.

Example:-

Output:-

swift_higher_order_map

Filter –

It loops over array elements and returns an array contains only elements that satisfy filter specified in your closure.

Example:-

Output:-

swift_higher_order_function_filter

Reduce –

The reduce function combine all items in a collection to create a single new value. The Reduce function takes two parameters, an initial value of the result and a closure which takes two arguments, one is the initial value or the result from the previous execution of the closure and the other one is the next item in the collection.

Example:-

Here, the initial value ($0) will be 0 and then the value from nums array is added to the initial value, which is retained for next iteration. In the end, one single value is returned

Output:-

swift_higher_order_function_reduce

In this tutorial we have learn about the Swift Higher Order functions and its application with practical example. I hope you will like this tutorial.