Swift add all elements from an array together

I have an array of numbers, and I want to iterate over all the elements in this array and combine all the integers. Here is the function that 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 will probably have to do this inside a while loop. Can someone give me some guidance on where to go from here? Thanks!

+6
source share
1 answer

No loop needed. Use reduce , for example:

 let sum = array.reduce(0,+) 
+21
source

Source: https://habr.com/ru/post/979713/


All Articles