Skip to content

Higher-Order Functions

Higher-order functions are functions that either take one or more functions as arguments or return a function as their result. In Swift, these are commonly used with collections to write expressive, declarative code.

Map

map iterates over a collection and transforms every item using a named function or a closure you provide. It returns a new array containing the transformed items.

swift
let numbers = [1, 2, 3, 4, 5]

// Double every number
let doubled = numbers.map { (number: Int) -> Int in
    return number * 2
}

print(doubled) // [2, 4, 6, 8, 10]

Filter

filter iterates over a collection and returns a new array containing only the elements that satisfy a specific condition.

swift
let names = ["Jack", "James", "Anne", "John"]

// Filter names starting with 'J'
let jNames = names.filter { (name: String) -> Bool in
    return name.hasPrefix("J")
}

print(jNames) // ["Jack", "James", "John"]

Reduce

reduce combines all items in a collection into a single value. It takes an initial value and a named function or a closure that describes how to combine the current accumulated value with the next item.

swift
let prices = [10, 20, 30, 40]

// Sum all prices starting from 0
let total = prices.reduce(0) { (runningTotal: Int, nextPrice: Int) -> Int in
    return runningTotal + nextPrice
}

print(total) // 100

Shorthand Syntax

You can also write the code above using the shorthand syntax you learned earlier, as shown below:

swift
// Shorthand argument names
let totalShorthand = prices.reduce(0) { $0 + $1 }

// Operator Shorthand, since the '+' operator perfectly matches the closure signature
let totalOperator = prices.reduce(0, +)

CompactMap

compactMap is similar to map, but it automatically removes nil values from the resulting array. This is extremely useful when converting types that might fail.

swift
let strings = ["1", "2", "three", "4", "five"]

// Convert to Int? and remove nil values
let ints = strings.compactMap { Int($0) }

print(ints) // [1, 2, 4]

Sorted

sorted returns a new collection that is sorted based on a named function or a closure that compares two elements.

swift
let unsorted = [5, 1, 4, 2, 3]

// Sort descending
let descending = unsorted.sorted { $0 > $1 }

// You can also use the Operator Shorthand here
let descendingOperator = unsorted.sorted(by: >)

print(descending) // [5, 4, 3, 2, 1]
print(descendingOperator) // [5, 4, 3, 2, 1]

ForEach

forEach iterates over a collection and performs an action for each element. Unlike map, it does not return a new array and is used purely for performing actions, such as printing values or updating an interface.

swift
let names = ["Alice", "Bob", "Charlie"]

names.forEach { (name: String) in
    print("Hello, \(name)!")
}