extension Array {
func reduce<T>(_ initial: T, combine: (T, Element) -> T) -> T {
var result = initial
for x in self {
result = combine(result, x)
}
return result
}
}
How does the below function work when it only passes a * to the combine closure?
func productUsingReduce(integers: [Int]) -> Int {
return integers.reduce(1, combine: *)
}
CodePudding user response:
static func * (lhs: Self, rhs: Self) -> Self is an operator function defined on the Numeric protocol. So, you are really just passing in a function that takes two arguments.
CodePudding user response:
What does the declaration mean?
combine: (T, Element) -> T
It says: the combine
parameter is a function that takes two parameters, a T and an Element, and returns a T.
Well, in Swift, operators are functions, and *
is such a function. So it suffices to pass a reference to this function as the combine
parameter. The bare name, *
, is that reference.