Adding Items in an Array

If an array contains numbers such as integers or decimal numbers, it’s fairly simple to write a function that adds all the elements of an array using a for-in loop. For example, assume you have an array of integers like this:

var transactions = [3, 56, 1, 20, 38, 7]

Now to add all these integers in the array together, start by assuming the total value is 0. Then keep adding each array item until you get a total. A for-in loop might look like this:

var myTotal = 0
for i in transactions {
    myTotal = myTotal + i
}

This for-in loop is straightforward, but Swift offers a method for manipulating arrays called reduce. The reduce method lets you define an initial value and a closure, which is essentially the guts of a function written in condensed form. As an alternative to adding array items using a for-in loop, you could just use a closure like this:

var transactions = [3, 56, 1, 20, 38, 7]

var total: Int {
    return transactions.reduce(0, {x, y in x + y})
}

This defines an Int variable called “Total” that uses the reduce array method to calculate a value. In this case, the initial value is 0. Then it takes one value in the array (x) and adds it with the next value in the array (y). This gives us the exact same result as the for-in loop.

The for-in loop is obviously clearer and easier to understand. The reduce method with a closure is more elegant but harder to understand. Since closures can look so odd, it’s probably best to add comments that explain how they work and even write short code that duplicates what the closure does. This will help others better understand what the closure does and how it works.

To read more about the reduce method for arrays, click here.

 

December 6th, 2017 by
HTML Snippets Powered By : XYZScripts.com