Map and Filter Functions in Swift

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
July 25, 2023

Title: Map and Filter Functions in Swift

The map and filter functions in Swift are powerful tools that allow you to manipulate collections of data easily. Both functions are higher-order functions, meaning they can take other functions as parameters.

Map Function

The map function applies a given closure to each element in a collection, creating a new collection with the transformed values. It has the following syntax:

let numbers = [1, 2, 3, 4, 5]
let squaredNumbers = numbers.map { $0 * $0 }
print(squaredNumbers) // Output: [1, 4, 9, 16, 25]}

In the above example, the map function multiplies each number in the `numbers` array by itself, resulting in a new array `squaredNumbers` with the squared values.

Filter Function

The filter function allows you to create a new collection containing only the elements that satisfy a given condition. It has the following syntax:

let numbers = [1, 2, 3, 4, 5]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers) // Output: [2, 4]}

In the above example, the filter function selects only the even numbers from the `numbers` array, creating a new array `evenNumbers` containing `[2, 4]`.

Combining Map and Filter

You can also combine the map and filter functions to perform more complex transformations on collections. Here's an example:

let numbers = [1, 2, 3, 4, 5]
let squaredEvenNumbers = numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }
print(squaredEvenNumbers) // Output: [4, 16]}

In the above example, the code first filters the even numbers from the `numbers` array using the filter function, and then squares those even numbers using the map function. The final result is an array `squaredEvenNumbers` containing `[4, 16]`.

Both the map and filter functions are incredibly useful when working with collections, as they provide a concise and expressive way to transform and filter data.

Summary: Functions, Map, Filter, Collections, Transformations, Higher-order Functions, Swift