extension Array where Element == Int {
func prefixSum() -> [Int] {
var sum = 0
return map { element in
defer { sum += element }
return sum
}
}
func suffixSum() -> [Int] {
reversed().prefixSum().reversed()
}
}
The code above perfectly works.
The question is why does it work?
The function reversed()
returns not an Array. It returns ReversedCollection<Array>
. So result of reversed()
should not have function prefixSum()
defined. And returning type also should mismatch: function suffixSum()
expects an Array to be returned.
I thought suffixSum()
should be written like this (which, of course, also works):
func suffixSum() -> [Int] {
Array(Array(reversed()).prefixSum().reversed())
}