Give your simulator superpowers

RocketSim: An Essential Developer Tool
as recommended by Apple

Swift Reduce: Combining elements into a single value

The Swift reduce method allows you to produce a single value from a collection of items. You can use it to convert an array into a dictionary or another common example is to reduce numbers and sum them up. This introduction should pique your interest in swift reduce.

Reduce is a typical functional pattern, a higher-order function that combines a collection into a single value cleanly and expressively. Its complexity is O(n), where n is the length of the sequence. With that in mind, it’s time to dive into some swift reduce examples!

The Basics of Reduce

At its core, reduce takes two arguments:

  1. An initial value
  2. A closure that specifies how to combine each element with the accumulating result

Here’s an example that sums up an array of integers:

Swift reduce allows you to combine a collection of elements into a single result.
Swift reduce allows you to combine a collection of elements into a single result.

In this case, 0 is the initial value. The closure takes the running total (result) and adds each number from the array to it. Initially, result will be 0, but it will grow accordingly after adding more and more elements.

You can simplify the closure using shorthand syntax:

let total = numbers.reduce(0, +)

This works because + is a function that takes two numbers and returns their sum. Notice how swift reduce can make your code more concise.

How do you stay current as a Swift developer?

Let me do the hard work and join 20,278 developers that stay up to date using my weekly newsletter:

Creating a Dictionary with Reduce

Reduce becomes even more interesting when transforming an array into a dictionary. Let’s say you have an array of people and want to group them by the first letter of their name. Here, the swift reduce method shines in its versatility

let names = ["Antoine", "Maaike", "Jaap", "Jip"]
let grouped: [String: [String]] = names.reduce(into: [:]) { result, name in
    let firstLetter = String(name.first!)
    result[firstLetter, default: []].append(name)
}
// grouped == ["M": ["Maaike"], "A": ["Antoine"], "J": ["Jaap", "Jip"]]

This version uses reduce(into:), a mutable variant of reduce. It avoids copying the accumulator on each iteration, making swift reduce more efficient for some instances.

Exploring useful cases

To better understand the reduce method, it’s convenient to look at a few common examples.

Counting occurrences

Count how often each element appears in an array by reducing into a dictionary. Using swift reduce, we can achieve this efficiently:

let animals = ["Dog", "Cat", "Dog", "Bird"]
let counts = animals.reduce(into: [:]) { result, animal in
    result[animal, default: 0] += 1
}
// counts == ["Dog": 2, "Cat": 1, "Bird": 1]

Flattening nested arrays

You can also use reduce to flatten arrays of arrays. This is another great way to see swift reduce in action:

let nested = [[1, 2], [3, 4], [5]]
let flat = nested.reduce([], +)
// flat == [1, 2, 3, 4, 5]

The + operator adds each element of the nested arrays to the resulting array, which is a clean way to combine everything into one.

Should you always use Reduce?

While reduce is elegant and expressive, it’s not always the most readable option, especially for those unfamiliar with functional patterns. For simple sums or counts, it’s great. Consider readability and whether a for-loop might communicate your intent better for more complex logic. That said, mastering swift reduce can be very rewarding.

Conclusion

The reduce method is a great way to combine multiple values into a single one. It’s commonly used to transform arrays into dictionaries or sum up a number collection. Just remember to balance elegance with readability. Swift reduce is a powerful tool in your programming arsenal.

If you like to improve your Swift knowledge, even more, check out the Swift category page. Feel free to contact me or tweet to me on Twitter if you have any additional tips or feedback.

Thanks!

 
Antoine van der Lee

Written by

Antoine van der Lee

iOS Developer since 2010, former Staff iOS Engineer at WeTransfer and currently full-time Indie Developer & Founder at SwiftLee. Writing a new blog post every week related to Swift, iOS and Xcode. Regular speaker and workshop host.

Are you ready to

Turn your side projects into independence?

Learn my proven steps to transform your passion into profit.