Member-only story

Swift’s Reduce Function

Higher-order

--

Photo by Jilbert Ebrahimi on Unsplash

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
}

The Example

The classic use of reduce is to sum an array and instead of using a while loop we can assign an initial value (0) and then the closure is applied sequentially to all element of the collection until a single final value is returned.

let sum = numbers.reduce(0, { sum, number in sum + number })
// sum is 15

This can be reduced (lol) using Swift’s shorthand arguments.

var numbers = [1,2,3,4]
numbers.reduce(0, {$0 + $1}) //10

The Power of Reduce

The beauty of reduce lies in its versatility. While it’s often used to sum numbers, it can perform any operation that combines elements into a single value. This could include multiplying elements, finding the maximum or minimum, concatenating strings, or even building a custom data structure.

--

--

Responses (1)