0
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())
}
Roman
  • 1,309
  • 14
  • 23
  • 7
    There are several overloads of `reversed()` and one of them returns an array. Compare https://stackoverflow.com/q/42688679/1187415 and https://stackoverflow.com/q/53321158/1187415. – Martin R Oct 02 '20 at 05:24
  • @MartinR Excellent. Thank you. – Roman Oct 02 '20 at 05:44
  • 1
    Generic implementation `extension Collection where Element: AdditiveArithmetic {` `var prefixSum: [Element] { indices.map { self[..<$0].reduce(.zero,+) } }` `var suffixSum: [Element] { indices.map { self[$0...].dropFirst().reduce(.zero,+) } }` `}` – Leo Dabus Oct 02 '20 at 07:05
  • 4
    @LeoDabus: That are O(n^2) implementations because every sum is calculated separately instead of O(n) where the each element is added to the previously calculated sum. – Martin R Oct 02 '20 at 07:13

0 Answers0