> 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-into-_.md).

# seq.reduce(into:\_:)

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

* [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(\_:\_:)](/ios/swift/collections/sequence/seq.reduce-_-_.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>(
    into initialResult: Result, 
    _ updateAccumulatingResult: (
        _ partialResult: inout Result,    // ⭐️ inout parameter
        Self.Element    
    ) throws -> ()                        // ⭐️ no return value
) rethrows -> Result
```

![](/files/P8fh2mtHCf5RcJBQh3De)

{% hint style="success" %}
使用此方法時，**一定要**在 <mark style="color:purple;">**updateAccumulatingResult**</mark> 這個 **closure** 的 **function body** 裡面更新 <mark style="color:purple;">**partialResult**</mark> 這個 <mark style="color:red;">**inout 參數**</mark>，<mark style="color:purple;">**reduce(into:\_:)**</mark> 就是透過**更新此參數**，最後再將此參數的**累積更新總結果** (<mark style="color:red;">**accumulating result**</mark>) 當成 <mark style="color:red;">**return value**</mark> 傳回。這也是為什麼這個 **closure** 稱為 <mark style="color:purple;">**updateAccumulatingResult**</mark> 了，因為你必須在它的 **body** 裡面 "<mark style="color:red;">**update**</mark>" <mark style="color:red;">**accumulating result**</mark> (<mark style="color:purple;">**partialResult**</mark>)。:point\_right: 比較：[seq.reduce(\_:\_:)](/ios/swift/collections/sequence/seq.reduce-_-_.md)
{% endhint %}

{% hint style="warning" %} <mark style="color:orange;">**註**</mark>：我認為 Apple 在這個方法的參數名稱上，有「**命名不一致**」的問題。既然 closure 稱為 <mark style="color:purple;">**updateAccumulatingResult**</mark>，那麼 <mark style="color:purple;">**partialResult**</mark> 這個 inout 參數就應該命名為 <mark style="color:orange;">**accumulatingResult**</mark> 才比較一致。
{% endhint %}

{% hint style="info" %}
This method 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" %}
👉 [stackoverflow](https://stackoverflow.com/a/47613755/5409815)

```swift
let numbers = [1, 1, 2, 2, 2, 3, 4, 4, 5, 4, 3]

// ⭐️ filter adjacent equal entries: [1, 2, 3, 4, 5, 4, 3]
//                                  ╭──1──╮    ╭─2──╮
let filtered = numbers.reduce(into: [Int]()) { result, n in
    if n != result.last { result.append(n) }
//                        ╰───── 3 ──────╯
}
// ⭐️ 1. intial result: empty array
// ⭐️ 2. accumulating result (inout parameter)
// ⭐️ 3. update accumulating result in closure body
```

{% endtab %}

{% tab title="2" %}

```swift
let letters = "abracadabra"

// ⭐️ letter frequencies of a string
// ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1]
//                   ╭1╮    ╭─2──╮
letters.reduce(into: [:]) { counts, letter in
    counts[letter, default: 0] += 1
//  ╰───────────── 3 ─────────────╯
}
// ⭐️ 1. intial result: empty dictionary
// ⭐️ 2. accumulating result (inout parameter)
// ⭐️ 3. update accumulating result in closure body
```

{% endtab %}
{% endtabs %}
