seq.reduce(_:_:)

// declaration
func reduce<Result>(
    _ initialResult    : Result, 
    // โญ๏ธ combine function (with return value)
    _ nextPartialResult: (Result, Element) throws -> Result
) rethrows -> Result
  • ๅช่ฆ่จญๅฎšไธ€ๅ€‹ๅˆๅง‹ๅ€ผ (initialResult)๏ผŒๆญคๆ–นๆณ•ๅฐฑๆœƒไฝฟ็”จ nextPartialResult ้€™ๅ€‹ closure ไพ†้€ฒ่กŒ็ดฏ็ฎ—๏ผŒไธฆๅฐ‡ๆœ€ๅพŒ็š„็ดฏ็ฎ—็ตๆžœๅ›žๅ‚ณใ€‚๐Ÿ‘‰ ๆฏ”่ผƒ๏ผšseq.reduce(into:_:)

on every execution of the combine function, a brand-new array is being created by appending the transformed or included element to the previous one. This means that both these implementations are O(nยฒ), not O(n) ...

๐Ÿ‘‰ Advanced Swift, p.37

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

๐Ÿ‘‰ .reduce(into:_:)

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

Last updated