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.
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]
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?