Avatar ·

How to find the sum of array elements in Swift? Finding the sum of numbers

Hello everyone! I just started learning Swift and I have a problem with arrays. I need to find the sum of all elements in an array of numbers. I wrote this code, but it doesn't work and I don't understand why: ```swift let numbers = [1, 2, 3, 4, 5] var sum = 0 for i in numbers { sum = sum + numbers[i] } print(sum) ``` It gives an error: "Cannot convert value of type 'Int' to expected argument type 'Index'". I thought that `i` is the index of the element, but apparently I'm wrong. How do I properly iterate through the array and add all the numbers? Is there a built-in function for this? I've heard about `reduce`, but I don't quite understand how it works. I would also like to know how to sum elements if the array is optional (e.g., `[Int]?`) or if it can contain nil values (e.g., `[Int]?`).