<!--
{
  "availability" : [
    "iOS: 13.0.0 -",
    "iPadOS: 13.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.15.0 -",
    "tvOS: 13.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 6.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Combine",
  "identifier" : "/documentation/Combine/Publisher/tryReduce(_:_:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Combine"
    ],
    "preciseIdentifier" : "s:7Combine9PublisherPAAE9tryReduceyAA10PublishersO03TryD0Vy_xqd__Gqd___qd__qd___6OutputQztKctlF"
  },
  "title" : "tryReduce(_:_:)"
}
-->

# tryReduce(_:_:)

Applies an error-throwing closure that collects each element of a stream and publishes a final result upon completion.

```
func tryReduce<T>(_ initialResult: T, _ nextPartialResult: @escaping (T, Self.Output) throws -> T) -> Publishers.TryReduce<Self, T>
```

## Parameters

`initialResult`

The value that the closure receives the first time it’s called.

`nextPartialResult`

An error-throwing closure that takes the previously-accumulated value and the next element from the upstream publisher to produce a new value.

## Return Value

A publisher that applies the closure to all received elements and produces an accumulated value when the upstream publisher finishes.

## Discussion

Use [`tryReduce(_:_:)`](/documentation/Combine/Publisher/tryReduce(_:_:)) to collect a stream of elements and produce an accumulated value based on an error-throwing closure you provide.
If the closure throws an error, the publisher fails and passes the error to its subscriber.

In the example below, the publisher’s `0` element causes the `myDivide(_:_:)` function to throw an error and publish the <doc://com.apple.documentation/documentation/Swift/Double/nan> result:

```
struct DivisionByZeroError: Error {}
func myDivide(_ dividend: Double, _ divisor: Double) throws -> Double {
    guard divisor != 0 else { throw DivisionByZeroError() }
    return dividend / divisor
}

var numbers: [Double] = [5, 4, 3, 2, 1, 0]
numbers.publisher
    .tryReduce(numbers.first!, { accum, next in try myDivide(accum, next) })
    .catch({ _ in Just(Double.nan) })
    .sink { print("\($0)") }
```

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)