> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/swift/collections/sequence/seq.reduce-_-_.md).

# seq.reduce(\_:\_:)

{% tabs %}
{% tab title="📘 手冊" %}

1. [Swift](https://developer.apple.com/documentation/swift) ⟩ [Sequence](https://developer.apple.com/documentation/swift/sequence) ⟩
   * [.reduce()](https://developer.apple.com/documentation/swift/sequence/2907677-reduce)
   * [.reduce(into:\_:)](https://developer.apple.com/documentation/swift/sequence/3128812-reduce)
     {% endtab %}

{% tab title="📗 參考" %}

1. Advanced Swift, p.37
   {% endtab %}

{% tab title="👥 相關" %}

1. [seq.reduce(into:\_:)](/ios/swift/collections/sequence/seq.reduce-into-_.md)
2. [reduce() vs. reduce(into:)](/ios/swift/collections/sequence/reduce-vs-reduceinto.md)
3. [seq.stateMap(\_:\_:)](/ios/swift/collections/sequence/seq.statemap-_-_.md)
   {% endtab %}
   {% endtabs %}

```swift
// declaration
func reduce<Result>(
    _ initialResult    : Result, 
    // ⭐️ combine function (with return value)
    _ nextPartialResult: (Result, Element) throws -> Result
) rethrows -> Result
```

![](/files/TFuvcluKgU6rPJ6S0XCa)

{% hint style="info" %}

* 只要設定一個**初始值** (<mark style="color:purple;">**initialResult**</mark>)，此方法就會使用 <mark style="color:purple;">**nextPartialResult**</mark> 這個 **closure** 來進行累算，並將**最後的累算結果**回傳。:point\_right: 比較：[seq.reduce(into:\_:)](/ios/swift/collections/sequence/seq.reduce-into-_.md)
  {% endhint %}

{% hint style="danger" %}
on <mark style="color:red;">**every execution**</mark> of the <mark style="color:red;">**combine function**</mark>, a <mark style="color:red;">**brand-new array**</mark> is being **created** by appending the transformed or included element to the previous one. This means that both these implementations are <mark style="color:purple;">**O(n²)**</mark>, not O(n) ...

👉 Advanced Swift, p.37
{% endhint %}

{% hint style="success" %}
[.reduce(into:\_:)](https://developer.apple.com/documentation/swift/sequence/3128812-reduce) is <mark style="color:red;">**preferred**</mark> over [`reduce(_:_:)`](/ios/swift/collections/sequence/seq.reduce-_-_.md) for <mark style="color:red;">**efficiency**</mark> when the <mark style="color:red;">**result**</mark> is a <mark style="color:red;">**copy-on-write**</mark> type, for example an <mark style="color:red;">**Array**</mark> or a <mark style="color:red;">**Dictionary**</mark>.

👉 [.reduce(into:\_:)](https://developer.apple.com/documentation/swift/sequence/3128812-reduce)
{% endhint %}

{% tabs %}
{% tab title="1" %}

```swift
let numbers = [1, 2, 3, 4]
let sum = numbers.reduce(0, +)        // 10
```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}
