Swift - Higher-Order Functions



A higher-order function is a special type of function; it takes one or more functions as arguments or can return a function as its result. They can easily manipulate and transform the data of the given collections without creating any extra user-defined function. Below are the higher-order functions provided by the Swift language −

  • forEach()
  • map()
  • compactMap()
  • flatMap()
  • filter()
  • reduce()
  • sort()
  • sorted()

All the higher-order functions are based on closure but don't worry you don't need to be a master of closure. They are easy to use and also reduce the size of the code in the project and can be reusable.

The forEach() Function

The ForEach() function is quite similar to the for-in loop. It will iterate through all the elements in a collection (eg array) and not return anything. Remember that you cannot use continue and break inside the forEach() function to exit the currently executing statement.

Syntax

Following is the syntax of the forEach() function −

func forEach(_x: (Self.Element)throws-> Void) rethrows

Parameter

x represents a closure that takes an item of the given sequence as a parameter.

Example

Swift program to display all the elements of the array using the forEach() function.

import Foundation

let numbersInWord = ["One", "Two", "Three", "Four", "Five", "Six"]
numbersInWord.forEach { 
   element in print(element)
}

Output

It will produce the following output −

One
Two
Three
Four
Five
Six

The map() Function

The map function works by performing an operation on all the elements of a collection and returning a new collection with the results of that operation. This function is designed to transform an object from one type to another type (as well as the same type).

Syntax

Following is the syntax of the map() function −

func map<T>(_ mTransform: (Self.Element) throws -> T) rethrows -> [T]

Parameter

The mTransform is a mapping closure. It accepts elements from the given sequence and returns a transformed value of the same or different type.

Return Value

It will return a transformed array.

Example

Swift program to convert int to a string using the map() function.

import Foundation

let numbers = [1, 2, 3, 4, 5, 6, 7]
let numbersInString = numbers.map { 
   number in String(number)
}
print("numbersInString: \(numbersInString)")

Output

It will produce the following output −

numbersInString: ["1", "2", "3", "4", "5", "6", "7"]

The compactMap() Function

Iterating through the elements in an array, compactMap() returns an updated array only containing elements that satisfy the condition stated within its body. The array will be updated without any elements that result in a nil value. Or we can say that the compactMap() loops through all the elements in the array and returns non-nil values.

Syntax

Following is the syntax of the compactMap() function −

Func compactMap<ElementOfResult>(_ mTransform: 
(Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]

Parameter

The mTransform is a closure. It accepts elements from the given sequence and returns an optional value.

Return Value

It will return a transformed array of non-nil values.

Example

Swift program to convert string array to an integer array using the comapctMap() function.

import Foundation

let numbersInString = ["1", "x2", "3", "4", nil, "five5"]
let validNumbers = numbersInString.compactMap { 
   stringValue in
   Int(stringValue ?? "")
}
print("validNumbers: \(validNumbers)")

Output

It will produce the following output −

validNumbers: [1, 3, 4]

The flatMap() Function

The flatMap() function allows us to transform a set of arrays into a single set that contains all of the elements. It concatenates the elements of specified collections into a resultant collection.

Syntax

Following is the syntax of the flatMap() function −

func map<SegmentOfResult>(_ mTransform: 
(Self.Element) throws -> SegmentOfResult) rethrows -> 
[SegmentOfResult.Element] where SegmentOfResult : Sequence

Parameter

The mTransform is a closure. It accepts elements from the given sequence and returns a sequence.

Return Value

It will return a flattened array.

Example

Swift program to convert a multi-dimensional array into a one-dimensional array using the flatMap() function.

import Foundation

let marks = [[3, 4, 5], [2, 5, 3], [1, 2, 2], [5, 5, 4], [3, 5, 3]]
let allMarks = marks.flatMap { 
   marksArray -> [Int] in
   marksArray
}
print("allMarks: \(allMarks)")

Output

It will produce the following output −

allMarks: [3, 4, 5, 2, 5, 3, 1, 2, 2, 5, 5, 4, 3, 5, 3]

The filter() Function

The filter() will iterate through all elements in an array and will return an updated array only with the elements that satisfy the condition written inside the body of the filter. It is an essential function. While you write code, many times you need to filter out collections to produce a filtered collection based on a condition.

The return type of the closure is a Bool value; items in the resulting array are those that satisfy the condition inside the body;

Syntax

Following is the syntax of the filter() function −

func filter(_ resultantCollection: (Self.Element) throws -> Bool) rethrows -> Self

Parameter

The resultantCollection is a closure. It accepts elements from the given sequence and returns a boolean value which indicates whether the element should included in the resultant collection or not.

Return Value

It will return a collection that contains only those items that satisfy the condition inside the body.

Example

Swift program to display only positive numbers from the given array using the filter() function.

import Foundation

let numbers = [-12, 23, -1, 56, 9, -2, 0, 14, 8]
let positives = numbers.filter { 
   number in
   number > 0
}
print("positives: \(positives)")

Output

It will produce the following output −

positives: [23, 56, 9, 14, 8]

The reduce() Function

The reduce() function will iterate through all elements in an array and return an object with the combined value of all elements.

Syntax

Following is the syntax of the reduce() function −

func reduce<Result>(_initialRes: Result, _nestRes: (Result, Self.Element) throws -> T) 
rethrows -> Result) rethrows->Result

Parameter

This function takes two parameters −

  • The parameter initialRes is used to store initial accumulating value which is further passed to the nextRes at the first time the closure is executed.

  • The nextRes is a closure that is used to combine accumulating value and an element of the sequence into a new accumulating value, which is further used in the next call of the nextRes closure.

Return Value

It will return the final value. Or if the sequence contains no items then it will return initialRes.

Example

Swift program to find the sum of the array elements using the reduce() function.

import Foundation

let numbers = [1, 5, 2, 10, 6]
let sum = numbers.reduce(0) { 
   (result, number) -> Int in
   result + number
}
print("sum:", sum)

Output

It will produce the following output −

sum: 24

The sort() Function

The sort() function will sort all elements of the given collection in ascending order. It can also sort elements in descending order.

Syntax

Following is the syntax of the sort() function −

func sort()

Parameter

It does not take any parameters.

Return Value

It will return a sorted collection.

Example

Swift program to sort the elements of the array using the sort() function.

import Foundation

var numbers = [1, 5, 2, 10, 6]
numbers.sort()
print("Sorted numbers: \(numbers)")

Output

It will produce the following output −

Sorted numbers: [1, 2, 5, 6, 10]

The sorted() Function

The sorted() function will sort all elements according to the condition written inside the body of the closure and return a new sorted array. It can sort elements in ascending and descending order.

Syntax

Following is the syntax of the sorted() function −

func sorted()

Parameter

It does not take any parameters.

Return Value

It will return a sorted collection.

Example

Swift program to sort the elements of the array using the sorted() function.

import Foundation

var numbers = [1, 5, 2, 10, 6]
let sorted_values = numbers.sorted()
print("Sorted numbers: \(sorted_values)")

Output

It will produce the following output −

Sorted numbers: [1, 2, 5, 6, 10]
Advertisements