Higher Order Functions In Swift
Higher-order functions in iOS (or Swift) are functions that meet at least one of the following criteria:
- Take other functions as arguments
- Return other functions as their result
These functions are key elements of functional programming in Swift, allowing concise, readable, and expressive code.
Common Higher-Order Functions in Swift
1. map
Transforms each element of a collection and returns a new collection with the transformed values.
let numbers = [1, 2, 3, 4]
let squaredNumbers = numbers.map { $0 * $0 }
print(squaredNumbers) // Output: [1, 4, 9, 16]2. filter
Filters a collection based on a condition and returns a new collection containing only the elements that satisfy the condition.
let numbers = [1, 2, 3, 4, 5]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers) // Output: [2, 4]3. reduce
Reduces a collection into a single value by applying a closure repeatedly to combine elements.
let numbers = [1, 2, 3, 4]
let sum = numbers.reduce(0) { $0 + $1 }
print(sum) // Output: 10Get Himansu Panigrahi’s stories in your inbox
Join Medium for free to get updates from this writer.
4. forEach
Iterates through each element in a collection, executing a closure for each element.
let names = ["Alice", "Bob", "Charlie"]
names.forEach { print($0) }
// Output:
// Alice
// Bob
// Charlie5. compactMap
Transforms a collection into a new collection, removing nil values from the result.
let numbers = ["1", "2", "three", "4"]
let validNumbers = numbers.compactMap { Int($0) }
print(validNumbers) // Output: [1, 2, 4]6. flatMap
Flattens a collection of collections into a single-level collection.
let array = [[1, 2], [3, 4], [5, 6]]
let flattenedArray = array.flatMap { $0 }
print(flattenedArray) // Output: [1, 2, 3, 4, 5, 6]Custom Higher-Order Functions
You can also define your own higher-order functions by using function types as parameters or return types:
// Function that accepts another function as a parameter
func applyOperation(_ a: Int, _ b: Int, operation: (Int, Int) -> Int) -> Int {
return operation(a, b)
}
let sum = applyOperation(5, 3) { $0 + $1 }
print(sum) // Output: 8Why Use Higher-Order Functions?
- Conciseness: Reduce boilerplate code and improve readability.
- Expressiveness: Focus on “what to do” rather than “how to do it.”
- Immutability: Encourage functional patterns, reducing side effects.
- Chainability: Combine operations for a streamlined workflow.
Higher-order functions are widely used in iOS development, especially when working with collections, handling asynchronous tasks, and managing functional patterns.







