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.
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:-
1 2 3 4 |
let weekdays:[String] = ["sun" ,"mon" , "tue" ,"wed" , "thu", "fri", "sat"] let daysInCaps = weekdays.map { $0.uppercased()} print("W3Adda- Higher Order Function Map") print(daysInCaps) |
Output:-
Filter –
It loops over array elements and returns an array contains only elements that satisfy filter specified in your closure.
Example:-
1 2 3 4 |
var numbers = [1, 2, 3, 4, 5, 6, 7, 8] var oddNumbers = numbers.filter{ $0 % 2 == 1 } print("W3Adda- Higher Order Function Filter") print(oddNumbers); |
Output:-
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:-
1 2 3 4 |
var nums= [1, 2, 3, 4, 5, 6, 7, 8] let sumOfNumbers = nums.reduce(0,{$0 + $1}) print("W3Adda- Higher Order Function Reduce") print(sumOfNumbers) |
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:-