Sling Academy
Home/Swift/Swift: 5 ways to find the sum of a numeric array

Swift: 5 ways to find the sum of a numeric array

Last updated: April 18, 2023

This practical, code-centric article will walk you through several different ways to calculate the sum of a numeric array (an array that only contains numerical elements) in Swift.

Using the reduce() method

You can use the reduce() method to apply a function to all the elements in the array and return a single value. The function takes two arguments: an accumulator and an element. The accumulator is the result of the previous iteration, and the element is the current element in the array. The function returns a new accumulator value that is used for the next iteration.

This example demonstrates how to use reduce() to get the sum of an array:

let numbers = [9, -3, 3, 5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let sum = numbers.reduce(0) { accumulator, element in
    accumulator + element
}

print(sum)

Output:

69

You can also use a shorthand syntax for the function by using $0 and $1 as the accumulator and element arguments. This will help you solve the task with just a single line of code (it looks cool but the drawback is the reduction of readability):

let numbers = [9, -3, 3, 5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// get the job done with only a single line of code
let sum = numbers.reduce (0) { $0 + $1 }

print(sum) // 69

Another single-line solution with reduce():

let numbers = [9, -3, 3, 5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// get the job done with only a single line of code
let sum = numbers.reduce(0, +)

print(sum) // 69

Using a classic for loop

In programming, a simple for loop is the key that can open a plethora of doors, and it’s still true in the context of this tutorial.

Example:

let numbers = [1, 2, 3, 4, 5]
var sum = 0
for number in numbers {
    sum += number
}

print(sum)

Output:

15

Using the forEach() method

Example:

let numbers = [1, 2, 3, 4, 5]
var sum = 0
numbers.forEach { number in
    sum += number
}

print(sum)

Output:

15

Using a while loop

Not much difference from the previous approach but I think it is still worth a look.

Example:

let numbers = [1, 2, 3, 4, 5]
var sum = 0
var index = 0
while index < numbers.count {
    sum += numbers[index]
    index += 1
}

print(sum)

Output:

15

Using a for/in loop

This example finds the sum of double elements in an array:

import Foundation

let numbers: [Double] = [1.5, 2.3, 5.8, 3.2, 10.7, -2.1, 4.5, 6.3, 7.8, 9.1]
var sum: Decimal = 0.0
for number in numbers {
    sum += Decimal(number)
}

print(sum)

Output:

49.1

Next Article: Swift: 3 ways to calculate the average of a numeric array

Previous Article: Swift: Ways to Calculate the Product of an Array

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)