Open In App

Higher-Order Functions in Swift

Last Updated : 02 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Higher-order functions are functions that take other functions as arguments or return functions as their output. These functions are an important aspect of functional programming, which is a programming paradigm that focuses on the use of functions to model computation. Higher-order functions enable developers to abstract common patterns of function applications and make code more concise and reusable.

In Swift, higher-order functions are a powerful tool for manipulating and transforming collections of data. Swift provides several higher-order functions as part of its standard library, including map, filter, reduce, and sorted. In this article, we will explore these functions in detail, along with some examples of how they can be used.

map

The map function takes closure as its argument and applies it to each element in a sequence, returning a new sequence of transformed elements. Here is the basic syntax for the map function:

Syntax:

let transformed = sequence.map(transform)

The transform closure is a function that takes an element of the sequence as its input and returns a transformed version of the element.

Example 1:

Here is an example of using the map function to double the values in an array of integers:

Swift




// Swift program to use map 
  
let numbers = [1, 2, 3, 4, 5]
  
// Double the elements of the given array using map
let doubled = numbers.map { $0 * 2 }
  
print(doubled)


Output:

[2, 4, 6, 8, 10]

In this example, the map function applies the closure { $0 * 2 } to each element in the numbers array, resulting in a new array with the values doubled.

You can also use the map function to transform elements of a sequence into a different type

Example 2:

Here we are using map function to convert an array of strings to an array of integers.

Swift




// Swift program to use map 
let strings = ["1", "2", "3", "4", "5"]
  
// Converting the array elements from string to int type
let integers = strings.map { Int($0)! }
  
print(integers)


Output:

[1, 2, 3, 4, 5]

In this example, the map function applies the closure { Int($0)! } to each element in the strings array, converting each string to an integer using the Int initializer.

compactMap

The compactMap function is similar to the map function, but it filters out any nil values from the resulting sequence. This can be useful when working with options, as it allows you to transform a sequence of optional values into a non-optional sequence while ignoring any nil values.

Syntax:

let transformed = sequence.compactMap(transform)

The transform closure is a function that takes an element of the sequence as its input and returns a transformed version of the element.

Example 1:

In the following example, we are using the compactMap function to transform an array of optional integers into a non-optional array:

Swift




// Swift program to use compactMap function 
let optionals: [Int?] = [1, 2, nil, 4, nil]
  
// Transforming an array of optional integers into a non-optional array
// Using compactMap
let integers = optionals.compactMap { $0 }
  
print(integers)


Output:

[1, 2, 4]

In this example, the compactMap() function applies the closure { $0 } to each element in the options array, resulting in a new array with the non-nil elements. Any nil values are automatically filtered out.

You can also use the compactMap function to transform elements of a sequence into a different type, just like with the map function. 

Example 2:

In the following example, we are using the compactMap() to convert an array of optional strings to an array of integers:

Swift




// Swift program to use compactMap function 
let optionals: [String?] = ["1", "2", "nil", "4", "nil"]
  
// Converting an array of optional strings to an array of integers
// Using compactMap() function
let integers = optionals.compactMap { Int($0!) }
print(integers)


Output:

[1, 2, 4]

In this example, the compactMap() function applies the closure { Int($0!) } to each element in the optionals array, converting each string to an integer using the Int initializer. Any nil values are automatically filtered out.

forEach

The forEach function is used to perform an action on each element of a sequence. Unlike the map function, which returns a new sequence of transformed elements, forEach does not return a value. Instead, it simply performs the specified action on each element of the sequence.

Syntax:

Here is the basic syntax for the forEach function:

sequence.forEach(perform)

The perform closure is a function that takes an element of the sequence as its input and performs an action on that element.

Example 1:

Here is the below example we are using the forEach function to print each element of an array of strings:

Swift




// Swift program to use forEach function 
let words = ["apple", "banana", "cherry"]
  
// Using forEach() function to print all the
// elements of the given array
words.forEach { print($0) }


 Output:

apple
banana
cherry

In this example, the forEach function applies the closure { print($0) } to each element in the words array, printing each element to the console.

You can also use the forEach function to perform more complex actions on each element of a sequence. 

Example 2:

In the following example, we are using forEach to increment a counter for each even element in an array.

Swift




// Swift program to use forEach() function 
var counter = 0
let numbers = [1, 2, 3, 4, 5]
  
// Counting even numbers
numbers.forEach { if $0 % 2 == 0 { counter += 1 } }
print(counter)


Output:

2

In this example, the forEach function applies the closure { if $0 % 2 == 0 { counter += 1 } } to each element in the numbers array, incrementing the counter variable for each even element.

filter 

The filter function takes closure as its argument and returns a new sequence containing only the elements that match a certain condition. Here is the basic syntax for the filter function:

Syntax:

let filtered = sequence.filter(include)

They include closure is a function that takes an element of the sequence as its input and returns a Boolean value indicating whether the element should be included in the filtered sequence.

Example 1:

Here is an example of using the filter function to select only the even numbers from an array:

Swift




// Swift program to use filter() function 
let numbers = [1, 2, 3, 4, 5]
  
// Select even numbers
let evens = numbers.filter { $0 % 2 == 0 }
print(evens)


Output:

[2, 4]

In this example, the filter function applies the closure { $0 % 2 == 0 } to each element in the numbers array, returning a new array containing only the elements that are even.

You can also use the filter function in combination with the map function to transform and select elements from a sequence. 

Example 2:

In the following example, we are using filter and map together to select and transform elements from an array:

Swift




// Swift program to use filter() function 
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  
// Transforming elements from an array
let evenSquares = numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }
  
print(evenSquares)  


Output:

[4, 16, 36, 64, 100]

In this example, the filter function first selects only the even numbers from the numbers array, and then the map function squares each of those numbers.

Sorted

The sorted function returns a new, sorted array of elements from a sequence. The elements are sorted according to the provided closure, which is a function that takes two elements as its input and returns a Boolean value indicating whether the first element should come before the second element in the sorted array. Here is the basic syntax for the sorted function:

Syntax:

let sorted = sequence.sorted(by: areInIncreasingOrder)

The areInIncreasingOrder closure is a function that takes two elements as its input and returns a Boolean value indicating whether the first element should come before the second element in the sorted array. The sorted function uses this closure to determine the order in which the elements should be sorted.

Example 1:

Here is an example of using the sorted function to sort an array of integers in ascending order:

Swift




// Swift program to use sorted() function 
let numbers = [5, 3, 1, 4, 2]
  
// Sorting an array of integers in ascending order
let sortedNumbers = numbers.sorted(by: { $0 < $1 })
  
print(sortedNumbers)


Output:

[1, 2, 3, 4, 5]

In this example, the sorted function sorts the numbers array using the closure { $0 < $1 }, which compares the two elements and returns true if the first element is less than the second element.

You can also use the sorted function to sort elements in descending order. 

Example 2:

In the following example, we are using sorted to sort an array of strings in descending order:

Swift




// Swift program to use sorted() function 
let words = ["apple", "banana", "cherry", "date"]
  
// Sorting an array of integers in descending order
let sortedWords = words.sorted(by: { $0 > $1 })
  
print(sortedWords)


Output:

["date", "cherry", "banana", "apple"]

In this example, the sorted function sorts the words array using the closure { $0 > $1 }, which compares the two elements and returns true if the first element is greater than the second element.

reduce

The reduce function takes closure as its argument and combines all the elements in a sequence to produce a single value. Here is the basic syntax for the reduce function:

Syntax:

let result = sequence.reduce(initial, combine)

The initial value is the starting value for the reduction, and the combined closure is a function that takes two values as its input and returns a single, combined value. The combined closure is applied to the initial value and the first element of the sequence, and then to the result of that operation and the next element of the sequence, and so on until all the elements have been processed.

Example 1:

Here is an example of using the reduce function to calculate the sum of an array of integers:

Swift




// Swift program to use reduce() function 
let numbers = [1, 2, 3, 4, 5]
  
// Finding the sum of an array of integers
let sum = numbers.reduce(0, { $0 + $1 })
  
print(sum)


Output:

15

In this example, the reduce function starts with an initial value of 0 and combines each element in the numbers array with the running total using the closure { $0 + $1 }.

You can also use the reduce function to perform more complex operations, such as generating a string by concatenating the elements of an array. 

Example 2:

In the following example, we are using reduce to concatenate an array of strings:

Swift




// Swift program to use reduce() function 
let words = ["geeks", "for", "geeks"]
  
// Concatenating the array of string
let sentence = words.reduce("", { $0 + " " + $1 })
  
print(sentence)


Output:

geeks for geeks

In this example, the reduce function starts with an initial value of an empty string and combines each element in the words array with the running total using the closure { $0 + ” ” + $1 }.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads