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