From e4b83baa5307979f4650de116e33aaa0c3d7a202 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 28 Jan 2018 13:43:35 +0100 Subject: [PATCH] Cursor.reduce(into:_:) --- GRDB/Core/Cursor.swift | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 29a514499..81b5fc8b7 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -331,12 +331,30 @@ extension Cursor { /// Returns the result of calling the given combining closure with each /// element of this cursor and an accumulating value. - public func reduce(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) throws -> Result { - var result = initialResult + public func reduce( + _ initialResult: Result, + _ nextPartialResult: (Result, Element) throws -> Result) + throws -> Result + { + var accumulator = initialResult while let element = try next() { - result = try nextPartialResult(result, element) + accumulator = try nextPartialResult(accumulator, element) } - return result + return accumulator + } + + /// Returns the result of calling the given combining closure with each + /// element of this cursor and an accumulating value. + public func reduce( + into initialResult: Result, + _ updateAccumulatingResult: (inout Result, Element) throws -> Void) + throws -> Result + { + var accumulator = initialResult + while let element = try next() { + try updateAccumulatingResult(&accumulator, element) + } + return accumulator } /// Returns an array, up to the given maximum length, containing the