Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift add all elements from array together

I have an array of numbers and I want to iterate through all of the elements in that array and add together all of the integers. Here is the function I have so far:

func addTogether(array:Array<Int>, divide:Int) -> Int
{
    var a = 0

    while a < array.count
    {

    }

    return 0
}

I know that I'm probably going to have to do this inside of the while loop. Can anyone give me some guidance as to where to go from here? Thanks!

like image 655
Jim McDermott Avatar asked Dec 16 '14 16:12

Jim McDermott


People also ask

What does .append do in Swift?

Adds a new element at the end of the array.

How do I combine two arrays in Swift?

To append or concatenate two arrays in Swift, use plus + operator with the two arrays as operands.

Can we append array?

If you are using List as an array, you can use its append(), insert(), and extend() functions. You can read more about it at Python add to List. If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array.


1 Answers

No loop needed. Use reduce, like this:

let sum = array.reduce(0,+)
like image 125
matt Avatar answered Oct 06 '22 11:10

matt