How do I sort, filter, and map sequences in Swift?

In Swift, sorting, filtering, and mapping sequences are powerful operations that can be performed using higher-order functions. These functions allow developers to manipulate collections and sequences in a functional style, making the code cleaner and more expressive.

Sorting

To sort a collection, you can use the sorted() method. This method returns a new array that contains the sorted elements of the original collection.

Filtering

The filter(_:) method allows you to create a new array containing just the elements that satisfy a given predicate.

Mapping

With the map(_:) method, you can transform the elements of a collection to a new collection based on a provided closure.

Example

let numbers = [1, 2, 3, 4, 5] // Sorting the array let sortedNumbers = numbers.sorted() // Filtering the array let evenNumbers = numbers.filter { $0 % 2 == 0 } // Mapping the array let doubledNumbers = numbers.map { $0 * 2 } print("Sorted Numbers: \(sortedNumbers)") print("Even Numbers: \(evenNumbers)") print("Doubled Numbers: \(doubledNumbers)")

Swift Sorting Filtering Mapping Sequences Higher-order functions