Pitch: Method to sum numeric arrays

I agree with this.

I agree with this.

If you’re talking about making the result Optional, I strongly disagree. The empty sum is always equal to zero.

Yes, this is definitely related to @Erica_Sadun’s previous pitch.

Here is how the different options compare at the use-site:

nums.reduce(0, +)      // Current Swift
nums.reduce(+)         // Erica’s pitch
nums.sum()             // This pitch

It think it is abundantly self-evident that “sum” is much clearer at the point of use. The code is calculating a sum.

• • •

That code looks perfectly fine to me, if slightly more verbose than absolutely necessary. I would not call it “bad”.

Also, the examples in the original post do not actually show the proper way to sum this today:

expenses.reduce(0){ $0 + $1.amount }

The map example shown in the original post allocates an extraneous Array, which could be avoided by first calling lazy. For that reason, I would say the loop you referred to as “bad code” is actually significantly better code than the non-lazy map version.

• • •

I am unsure how frequently a mapping sum method would be used, but if it is a commonly employed operation then I agree it would be nice to write concisely:

expenses.sum{ $0.amount }    // closure
expenses.sum(\.amount)       // key-path
6 Likes