OneBite.Dev - Coding blog in a bite size

Find The Sum Of All Elements In An Array In Swift

Code snippet for how to Find The Sum Of All Elements In An Array In Swift with sample and detail explanation

In Swift, you may come across situations where you need to find the sum of all elements in an array. Fortunately, Swift’s base syntax provides a simple and efficient way to do this. Below is the code snippet and explanation on how you can achieve this task.

Code Snippet: Find The Sum Of All Elements In An Array In Swift

let numbers = [5, 10, 15, 20]
let sum = numbers.reduce(0, +)
print(sum) // prints: 50

Code Explanation for: Find The Sum Of All Elements In An Array In Swift

This short script in the Swift programming language accomplishes quickly what we’re looking for. Here’s a step-by-step to what this does:

  1. The first line of code let numbers = [5, 10, 15, 20] simply declares an array named numbers with four integer elements: 5, 10, 15, and 20.

  2. The second line of code let sum = numbers.reduce(0, +) is where the magic happens. This line is using the reduce function on our numbers array. The reduce function is used to combine all items in a collection to create a single new value. The parameters for this function are explained below:

    • The first argument 0 is the initial result value. You can think of this as a “starting point”. The computation begins at this provided value.

    • The second argument + can be seen as the combining closure or the formula used to combine the elements of the array. In this case, it is simply adding up the values (+ operator).

  3. The final line print(sum) // prints: 50 is simply printing the calculated sum of all elements in the array to your console.

To sum it up, this simple and efficient script allows us to quickly sum all elements in an array using Swift’s reduce function. You can apply this method to any array of numbers you need to sum in your Swift programming projects.

swift