I wonder how do I get the sum of some elements in an array? for example, here's my array and I only need to sum up the first 5 elements:
var num = [31, 28, 31, 30, 30, 31, 30, 31, 30, 29, 31, 31]
I tried doing it with range, but it didn't work out:
for I in 0..<num[5] {
.....
}
for I in 0..<nums[5]doesn't work the way you expect, becausenums[5]is saying "the fifth (0 indexed) element ofnums". So it's as if you wrote:which is not what you want.
To iterate over the first 5 elements of your
numarray, you'll want to slice it first. Here's two ways to do that:Ask for a 5-element prefix:
Slice it from the start, to its 5th element (at index 4):
This isn't as robust, because it'll crash if the array isn't long enough, unlike the
prefixbased approach (which just pulls as many as elements as available, up to 5 max.)Both of those answers would print the first 5 numbers (31, 28, 31, 30, 30).
To sum them, you'd either do it manually with a loop:
Or more succinctly with
reduce: