.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:
initialValue
stores the initial value or result returned by the closure from each iteration.closure
takes 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
initalValue
is 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
- Skill path
Build iOS Apps with SwiftUI
Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.Includes 7 CoursesWith CertificateBeginner Friendly13 hours - Free course
Learn Swift
A powerful programming language developed by Apple for iOS, macOS, and more.Beginner Friendly12 hours