arraysswiftfor-in-loop

Sum of some elements in an array


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] {
  .....
}

Solution

  • for I in 0..<nums[5] doesn't work the way you expect, because nums[5] is saying "the fifth (0 indexed) element of nums". So it's as if you wrote:

    for i in 0..<31 { ... }
    

    which is not what you want.

    To iterate over the first 5 elements of your num array, you'll want to slice it first. Here's two ways to do that:

    1. Ask for a 5-element prefix:

      for n in nums.prefix(5) { print(i) }
      
    2. Slice it from the start, to its 5th element (at index 4):

      for n in nums[...4] { print(i) }
      

      This isn't as robust, because it'll crash if the array isn't long enough, unlike the prefix based 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:

    var sum = 0
    
    for n in nums.prefix(5) { sum += n }
    
    print(sum)
    

    Or more succinctly with reduce:

    let sum = nums.prefix(5).reduce(0, +)