Get the sum of array elements in Swift


In this Swift tutorial, you are going to see how to get the sum of array elements of an integer-type array.

We can calculate the total of the array element if the elements are in number form. If the array is a string type, then it will cause a compilation error.

To calculate the sum of the array items, we are going to use the Swift reduce() method which is designed for converting a sequence into a single value. This feature of the reduce() method makes it a perfect choice for calculating the sum of elements of a Swift array.

Without going further, let’s create an array of integer types:

let intArray = [3, 7, 2]

Now below is the code for calculating the total of the elements of our array:

let sumArray = intArray.reduce(0, +)

Below is the complete code and output:

let intArray = [3, 7, 2]
let sumArray = intArray.reduce(0, +)

print("Sum of the array elements is \(sumArray)")

Output:

Sum of the array elements is 12

In the above code, you can see that we have passed two parameters in the reduce method. The first one is 0 which refers to it will start with 0.

The second parameter defines how the method should combine 0 with each item of the array. That means it will first calculate 0+3 as the first item is 3. Then the calculated value will be 3 and it will be further added to the second element which is 7 and calculate 3+7 which will be 10 and it continues adding until reaches the last item of the array. In the end, we will get the sum of all the elements of our array.

Also read: Remove duplicate elements from a Swift array

Calculate the sum of elements of a float type array

We can also calculate the sum of a float-type array in the same way as we did in the above example. Here we just have to pass a float type array.

See the example:

let floatArray = [1.43, 5.25, 3.65]
let sumArray = floatArray.reduce(0, +)

print("Sum of the array elements is \(sumArray)")

Output:

Sum of the array elements is 10.33

As you can see, we can also apply the reduce method to an array of float type to get the sum of the elements.