seq.reduce(into:_:)

// declaration
func reduce<Result>(
    into initialResult: Result, 
    _ updateAccumulatingResult: (
        _ partialResult: inout Result,    // ⭐️ inout parameter
        Self.Element    
    ) throws -> ()                        // ⭐️ no return value
) rethrows -> Result

This method is preferred over reduce(_:_:) for efficiency when the result is a copy-on-write type, for example an Array or a Dictionary.

👉 .reduce(into:_:)

👉 stackoverflow

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

Last updated

Was this helpful?