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?