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.

Higher-Order Functions in Swift

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.

Similar Reads

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:...

compactMap

...

forEach

...

filter

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....

Sorted

...

reduce

...