How do I use functional patterns like map/flatMap/compactMap?

In Swift, functional programming patterns like map, flatMap, and compactMap allow for more concise and expressive code. These methods are available on collections, such as arrays, and enable transformation and manipulation of data in a functional style.

Example Usage of Map, FlatMap, and CompactMap

Here’s a brief example demonstrating each of these methods:

// Example of an array of integers let numbers = [1, 2, 3, 4, 5] // Using map to square each number let squaredNumbers = numbers.map { $0 * $0 } print(squaredNumbers) // Output: [1, 4, 9, 16, 25] // Using flatMap to combine an array of arrays into a single array let nestedNumbers = [[1, 2], [3, 4], [5]] let flatNumbers = nestedNumbers.flatMap { $0 } print(flatNumbers) // Output: [1, 2, 3, 4, 5] // Using compactMap to unwrap Optionals and eliminate nil values let optionalNumbers: [Int?] = [1, nil, 3, nil, 5] let validNumbers = optionalNumbers.compactMap { $0 } print(validNumbers) // Output: [1, 3, 5]

functional programming Swift map flatMap compactMap array manipulation