Swift .reduce()
Anonymous contributor
Published Oct 24, 2022
Contribute to Docs
The .reduce() method loops or iterates over every item in a sequence, combines them into one value using a specified closure, and returns the combined result.
Syntax
arrayName.reduce(initialValue, closure)
The .reduce() method takes two arguments:
initialValuestores the initial value or result returned by the closure from each iteration.closuretakes 2 arguments. The first one is the result from previous execution of the closure, and the second one is next item in the collection.
Note: If the array has no elements, the
initalValueis returned.
Example
var values = [2,3,4,5]let sum = values.reduce(0, { x, y in x + y })print(sum)
In the example above, 0 is the initial value. x holds the result of the previous execution and y is the next item in the array. The closure performs an addition operation and returns the sum of all elements in the values array. This will output:
14
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Swift on Codecademy
- Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
- Includes 7 Courses
- With Certificate
- Beginner Friendly.13 hours
- A powerful programming language developed by Apple for iOS, macOS, and more.
- Beginner Friendly.12 hours