I've learned so far that the reduce() function in Swift is used to produce a single value from elements derived from an entire sequence. However, to my understanding the reduce() function requires two arguments to be called, the initialResult which is to be used in conjunction the second argument the nextPartialResult. An example implementation from the Swift documentation is below:
let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0, { x, y in
x + y
})
// numberSum == 10
However, in certain implementations of reduce() I have seen code such as the following:
let totalIncome = peopleArray.reduce(0) {(result, next) -> Double in
return result + next.income
}
print("Total Income: \(totalIncome) Average Income: \(totalIncome/Double(peopleArray.count))")
//Result: Total Income: 450000.0 Average Income: 150000.0
Code courtesy of codeburst
I am not sure whether this is a syntactical variation of writing the same thing (i.e. if somehow two arguments are indeed being passed into the reduce() function) or whether or not an argument is being omitted and if so, how that might affect the use cases of the function.
{(result, next) -> Double in return result + next.income }part is?-> Double. Btw the parentheses are not required.result, next infunc reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Int) throws -> Result) rethrows -> ResultThe first argument is the initial result0the second argument is thenextPartialResulta method which is being passed using a syntax called trailing closure (that's why it is after the closing parentheses). As I have already mentioned the type inferredResultwhich is aDoublein your second example is not needed in most cases.