What does Element mean when writing an extension on Array?
like in this example:
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
}
}
CodePudding user response:
The combine parameter is a function which takes a parameter of type T
and Element
. The Element is the actual Element of/in the array.
For example, this is an array of Int
elements:
let arr = [1,2,5,77]
In reduce, initial is of type T
. This is the staring value for the mapping you are about to perform.
In combine, T
is like your starting value for each subsequent step of combing the next Element to produce another value of type T
which will be used as the next T
in combine, and so and so forth until the entire array has been processed.
If you were using a default use of reduce such as:
arr.reduce(0, )
You can see that in this case, T
and Element
would both be of the same type, Int
.
However, I could have a custom object that the array is of, and my combine is defining how to get the running total. If you had something like this:
struct Thing {
var val1: String
var val2: Int
}
let thingArray = //...define some Things in an array
You could use reduce and define your own combine function to return the sum of all the val2 values. In this case, T
would be an Int
, and Element
would be Thing.