Swift running sum

前端 未结 7 1047
一生所求
一生所求 2020-12-01 18:25

I\'d like a function runningSum on an array of numbers a (or any ordered collection of addable things) that returns an array of the same length where each eleme

7条回答
  •  孤街浪徒
    2020-12-01 19:03

    If you just want it to work for Int, you can use this:

    func runningSum(array: [Int]) -> [Int] {
        return array.reduce([], combine: { (sums, element) in
            return sums + [element + (sums.last ?? 0)]
        })
    }
    

    If you want it to be generic over the element type, you have to do a lot of extra work declaring the various number types to conform to a custom protocol that provides a zero element, and (if you want it generic over both floating point and integer types) an addition operation, because Swift doesn't do that already. (A future version of Swift may fix this problem.)

提交回复
热议问题