Sitemap

Higher Order Functions In Swift

2 min readDec 5, 2024

--

Higher-order functions in iOS (or Swift) are functions that meet at least one of the following criteria:

  1. Take other functions as arguments
  2. 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: 10

Get 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
// Charlie

5. 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: 8

Why Use Higher-Order Functions?

  1. Conciseness: Reduce boilerplate code and improve readability.
  2. Expressiveness: Focus on “what to do” rather than “how to do it.”
  3. Immutability: Encourage functional patterns, reducing side effects.
  4. 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.

--

--

Himansu Panigrahi
Himansu Panigrahi

Written by Himansu Panigrahi

iOS Dev 📱 | Passionate about creating apps that solve real-world problems