Swift’s Reduce Function
Higher-order
I’ve previously written an article about implementing reduce, but never an article about the higher-order function reduce in Swift. It’s time to right that wrong.
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 15.0, and Swift 5.9
Prerequisites:
Be able to code Swift using Playgrounds
Terminology:
Higher-order function: A function that takes one or more functions as arguments or returns a function as its result.
Reduce: A higher-order function that returns the result of combining the elements of a sequence using a closure
The Basic Syntax
The reduce
function takes two parameters: an initial value and a closure that defines how to combine the elements. The closure is applied sequentially to all elements of the collection along with an accumulated value (which starts as the initial value), resulting in a single final value.
let numbers = [1, 2, 3, 4, 5]
let result = numbers.reduce(0) { accumulator, element in
// This closure (Int, Int) -> Int
// combines accumulator and element in some way to product
// a single Int
}