Higher-order functions are widely used for functional programming. Swift provides many built-in higher-order functions such as map
, filter
, reduce
, and compactMap
1. map
The map
function transforms each element in a collection by applying a closure.
let numbers = [1, 2, 3, 4, 5]
let squaredNumbers = numbers.map { $0 * $0 }
print(squaredNumbers) // Output: [1, 4, 9, 16, 25]
//
let numbers = [1, 2, 3, 4, 5]
let squaredNumbers = numbers.map { $0 * 2 }
print(squaredNumbers) // Output: [2, 4, 6, 8, 10]
//
let names = ["swift", "codewithswift", "swiftui"]
let uppercaseNames = names.map { $0.uppercased() }
print(uppercaseNames) // Output: ["SWIFT", "CODEWITHSWIFT", "SWIFTUI"]
2. filter
The filter
function filters elements of a collection based on a condition.
let numbers = [1, 2, 3, 4, 5]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers) // Output: [2, 4]
3.reduce
The reduce
function combines all elements of a collection into a single value.
let numbers = [1, 2, 3, 4, 5]
let sum = numbers.reduce(0) { $0 + $1 }
print(sum) // Output: 15
4.compactMap
The compactMap
function transforms a collection while removing any nil
values.
let strings = ["1", "2", "three", "4", "five"]
let numbers = strings.compactMap { Int($0) }
print(numbers) // Output: [1, 2, 4]
5.flatMap
flatMap
is a higher-order function similar to map
, but with an additional feature: it flattens or removes nesting from the resulting collection. It is useful when the transformation produces optional values or nested collections.
1.Removing nil Values
let strings = ["1", "2", "three", "4", "five"]
let numbers = strings.flatMap { Int($0) } // Converts valid strings to Int
print(numbers) // Output: [1, 2, 4]
2.Flattening Nested Arrays
let nestedArrays = [[1, 2, 3], [4, 5], [6, 7, 8]]
let flattenedArray = nestedArrays.flatMap { $0 }
print(flattenedArray) // Output: [1, 2, 3, 4, 5, 6, 7, 8]